<?php

/**
 * ECSHOP 订单管理
 * ============================================================================
 * 版权所有 2005-2010 上海商派网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.ecshop.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: yehuaixiao $
 * $Id: order.php 17219 2011-01-27 10:49:19Z yehuaixiao $
 */

define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . 'includes/lib_order.php');
require_once(ROOT_PATH . 'includes/lib_goods.php');

/*------------------------------------------------------ */
//-- 订单查询
/*------------------------------------------------------ */

if ($_REQUEST['act'] == 'order_query')
{
    /* 检查权限 */
    admin_priv('order_view');

    /* 载入配送方式 */
    $smarty->assign('shipping_list', shipping_list());

    /* 载入支付方式 */
    $smarty->assign('pay_list', payment_list());

    /* 载入国家 */
    $smarty->assign('country_list', get_regions());

    /* 载入订单状态、付款状态、发货状态 */
    $smarty->assign('os_list', get_status_list('order'));
    $smarty->assign('ps_list', get_status_list('payment'));
    $smarty->assign('ss_list', get_status_list('shipping'));

    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['03_order_query']);
    $smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => $_LANG['02_order_list']));

    /* 显示模板 */
    assign_query_info();
    $smarty->display('order_query.htm');
}

/*------------------------------------------------------ */
//-- 订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'list')
{   

    /* 检查权限 */
    admin_priv('order_view');

    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['02_order_list']);
    $smarty->assign('action_link', array('href' => 'order.php?act=order_query', 'text' => $_LANG['03_order_query']));

    $smarty->assign('status_list', $_LANG['cs']);   // 订单状态
    $smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
    $smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
    $smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
    $smarty->assign('full_page',        1);
    //待取消订单
    $order_list = order_list();
    $smarty->assign('time_start',    date("Y-m-d",(time()-86400*30)));
    $smarty->assign('time_end',    date("Y-m-d",time()+86400));
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    $smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');

    /* 显示模板 */
    assign_query_info();
    $smarty->display('order_list.htm');
}
/*导出订单*/
elseif ($_REQUEST['act'] == 'list_export')
{
    include_once('./includes/PHPExcel.php');
    error_reporting(E_ALL);
    date_default_timezone_set('Europe/London');
    $objPHPExcel = new PHPExcel();
    $name="订单列表";
    //设置表格属性
    $objPHPExcel->setActiveSheetIndex(0); 
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $objActSheet->getColumnDimension('A')->setWidth(20);
    $objActSheet->getColumnDimension('B')->setWidth(20);
    $objActSheet->getColumnDimension('C')->setWidth(20);
    $objActSheet->getColumnDimension('D')->setWidth(50);
    $objActSheet->getColumnDimension('E')->setWidth(15);
    $objActSheet->getColumnDimension('F')->setWidth(15);
    $objActSheet->getColumnDimension('G')->setWidth(15);
    // 标题写入
    $objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A1', '订单号')    
    ->setCellValue('B1', '下单时间')
    ->setCellValue('C1', '用户名')
    ->setCellValue('D1', '收货人/收货地址')
    ->setCellValue('E1', '支付方式')
    ->setCellValue('F1', '总金额')
    ->setCellValue('G1', '邮费');
    //导出数据写入
    $order_list = order_list_export();
    foreach($order_list as $k => $v){
            $num=$k+2;
            $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，uid是你查出数组的键值，下面以此类推
            ->setCellValue('A'.$num, ' '.strval($v['order_sn']))
            ->setCellValue('B'.$num, $v['add_time'])
            ->setCellValue('C'.$num, $v['buyer'])
            ->setCellValue('D'.$num, $v['consignee']."/".$v['address'])
            ->setCellValue('E'.$num, $v['pay_name'])
            ->setCellValue('F'.$num, $v['total_fee'])
            ->setCellValue('G'.$num, $v['shipping_fee']);
    }
    //设置格式
    $objPHPExcel->getActiveSheet()->setTitle('User');
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$name.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit();
}


/*------------------------------------------------------ */
//-- 售后订单列表
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'list_bought')
{
    /* 检查权限 */
    admin_priv('order_view');

    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['02_order_list']);
    $smarty->assign('action_link', array('href' => 'order.php?act=order_query', 'text' => $_LANG['03_order_query']));

    $smarty->assign('status_list', $_LANG['cs']);   // 订单状态

    $smarty->assign('os_unconfirmed',   OS_UNCONFIRMED);
    $smarty->assign('cs_await_pay',     CS_AWAIT_PAY);
    $smarty->assign('cs_await_ship',    CS_AWAIT_SHIP);
    $smarty->assign('full_page',        1);
    $smarty->assign('act',   $_REQUEST['act']);
    $order_list = order_list_bought();
    $smarty->assign('time_start',    date("Y-m-d",(time()-86400)));
    $smarty->assign('time_end',    date("Y-m-d",time()+86400));
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    $smarty->assign('sort_order_time', '<img src="images/sort_desc.gif">');
    /* 显示模板 */
    assign_query_info();
    $smarty->display('order_list_bought.htm');




}
/*导出售后订单*/
elseif ($_REQUEST['act'] == 'list_bought_export')
{               
    include_once('./includes/PHPExcel.php');
    error_reporting(E_ALL);
    date_default_timezone_set('Europe/London');
    $objPHPExcel = new PHPExcel();
    $name="售后订单列表";
    //设置表格属性
    $objPHPExcel->setActiveSheetIndex(0); 
    $objActSheet = $objPHPExcel->getActiveSheet(); 
    $objActSheet->getColumnDimension('A')->setWidth(15);
    $objActSheet->getColumnDimension('B')->setWidth(15);
    $objActSheet->getColumnDimension('C')->setWidth(15);
    $objActSheet->getColumnDimension('D')->setWidth(40);
    $objActSheet->getColumnDimension('E')->setWidth(50);
    $objActSheet->getColumnDimension('F')->setWidth(20);

    // 标题写入
    $objPHPExcel->setActiveSheetIndex(0)
    ->setCellValue('A1', '订单号')    
    ->setCellValue('B1', '下单时间')
    ->setCellValue('C1', '用户名')
    ->setCellValue('D1', '收货人/收货地址')
    ->setCellValue('E1', '售后信息')
    ->setCellValue('F1', '最后一次售后时间');
    //导出数据写入
    $order_list = order_list_bought_export();
    foreach($order_list as $k => $v){
            //获取订单全部售后信息
            $sql = "SELECT action_note FROM ".$ecs->table('order_action') ." WHERE order_id = $v[order_id] AND action_note LIKE  '%售后%'";
            $action_note_list= $db->getAll($sql);
            foreach ($action_note_list as $key => $value) {
                $action_note=$action_note.$value['action_note']."
";
            }


            $num=$k+2;
            $objPHPExcel->setActiveSheetIndex(0)
            //Excel的第A列，uid是你查出数组的键值，下面以此类推
            ->setCellValue('A'.$num, ' '.strval($v['order_sn']))
            ->setCellValue('B'.$num, $v['add_time'])
            ->setCellValue('C'.$num, $v['buyer'])
            ->setCellValue('D'.$num, $v['consignee']."/".$v['address'])
            ->setCellValue('E'.$num, $action_note)
            ->setCellValue('F'.$num, $v['log_time']);
    }
    //设置格式
    $objPHPExcel->getActiveSheet()->setTitle('User');
    $objPHPExcel->setActiveSheetIndex(0);
    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="'.$name.'.xls"');
    header('Cache-Control: max-age=0');
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    exit();
}
















/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query')
{
    /* 检查权限 */
    admin_priv('order_view');
    $order_list = order_list();
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    $sort_flag  = sort_flag($order_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
    make_json_result($smarty->fetch('order_list.htm'), '', array('filter' => $order_list['filter'], 'page_count' => $order_list['page_count']));
}
/*------------------------------------------------------ */
//-- 排序、分页、查询
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'query_bought')
{
    /* 检查权限 */
    admin_priv('order_view');
    $order_list = order_list_bought();
    $smarty->assign('order_list',   $order_list['orders']);
    $smarty->assign('filter',       $order_list['filter']);
    $smarty->assign('record_count', $order_list['record_count']);
    $smarty->assign('page_count',   $order_list['page_count']);
    $sort_flag  = sort_flag($order_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);
    make_json_result($smarty->fetch('order_list.htm'), '', array('filter' => $order_list['filter'], 'page_count' => $order_list['page_count']));

}










/*------------------------------------------------------ */
//-- 订单详情页面
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'info')
{
    /* 根据订单id或订单号查询订单信息 */
    if (isset($_REQUEST['order_id']))
    {
        $order_id = intval($_REQUEST['order_id']);
        $order = order_info($order_id);
    }
    elseif (isset($_REQUEST['order_sn']))
    {
        $order_sn = trim($_REQUEST['order_sn']);
        $order = order_info(0, $order_sn);
    }
    else
    {
        /* 如果参数不存在，退出 */
        die('invalid parameter');
    }

    /* 如果订单不存在，退出 */
    if (empty($order))
    {
        die('order does not exist');
    }

    /* 根据订单是否完成检查权限 */
    if (order_finished($order))
    {
        admin_priv('order_view_finished');
    }
    else
    {
        admin_priv('order_view');
    }

    /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
    $sql = "SELECT agency_id FROM " . $ecs->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
    $agency_id = $db->getOne($sql);
    if ($agency_id > 0)
    {
        if ($order['agency_id'] != $agency_id)
        {
            sys_msg($_LANG['priv_error']);
        }
    }

    /* 取得用户名 */
    if ($order['user_id'] > 0)
    {
        $user = user_info($order['user_id']);
        if (!empty($user))
        {
            $order['user_name'] = $user['user_name'];
        }
    }

    /* 取得所有办事处 */
    $sql = "SELECT agency_id, agency_name FROM " . $ecs->table('agency');
    $smarty->assign('agency_list', $db->getAll($sql));

    /* 取得区域名 */
    $sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
                "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
            "FROM " . $ecs->table('order_info') . " AS o " .
                "LEFT JOIN " . $ecs->table('region') . " AS c ON o.country = c.region_id " .
                "LEFT JOIN " . $ecs->table('region') . " AS p ON o.province = p.region_id " .
                "LEFT JOIN " . $ecs->table('region') . " AS t ON o.city = t.region_id " .
                "LEFT JOIN " . $ecs->table('region') . " AS d ON o.district = d.region_id " .
            "WHERE o.order_id = '$order[order_id]'";
    $order['region'] = $db->getOne($sql);

    /* 格式化金额 */
    if ($order['order_amount'] < 0)
    {
        $order['money_refund']          = abs($order['order_amount']);
        $order['formated_money_refund'] = price_format(abs($order['order_amount']));
    }
    /* 网仓状态 */
    if($order['wangcangstatus']){
        require_once(ROOT_PATH . 'languages/zh_cn/wangcang.php');
        $order['wangcangstatus'] = !empty($_LANG['status'][$order['wangcangstatus']])?$_LANG['status'][$order['wangcangstatus']]:'未知状态';
    }
    /* 其他处理 */
    $order['order_time']    = local_date($_CFG['time_format'], $order['add_time']);
    $order['pay_time']      = $order['pay_time'] > 0 ?
        local_date($_CFG['time_format'], $order['pay_time']) : $_LANG['ps'][PS_UNPAYED];
    $order['shipping_time'] = $order['shipping_time'] > 0 ?
        local_date($_CFG['time_format'], $order['shipping_time']) : $_LANG['ss'][SS_UNSHIPPED];
    $order['status']        = $_LANG['os'][$order['order_status']] . ',' . $_LANG['ps'][$order['pay_status']] . ',' . $_LANG['ss'][$order['shipping_status']];
    $order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];

    /* 取得订单的来源 */
    if ($order['from_ad'] == 0)
    {
        $order['referer'] = empty($order['referer']) ? $_LANG['from_self_site'] : $order['referer'];
    }
    elseif ($order['from_ad'] == -1)
    {
        $order['referer'] = $_LANG['from_goods_js'] . ' ('.$_LANG['from'] . $order['referer'].')';
    }
    else
    {
        /* 查询广告的名称 */
         $ad_name = $db->getOne("SELECT ad_name FROM " .$ecs->table('ad'). " WHERE ad_id='$order[from_ad]'");
         $order['referer'] = $_LANG['from_ad_js'] . $ad_name . ' ('.$_LANG['from'] . $order['referer'].')';
    }

    /* 取得订单商品总重量 */
    $weight_price = order_weight_price($order['order_id']);
    $order['total_weight'] = $weight_price['formated_weight'];

    /* 参数赋值：订单 */
    $smarty->assign('order', $order);

    /* 取得用户信息 */
    if ($order['user_id'] > 0)
    {
        /* 用户等级 */
        if ($user['user_rank'] > 0)
        {
            $where = " WHERE rank_id = '$user[user_rank]' ";
        }
        else
        {
            $where = " WHERE min_points <= " . intval($user['rank_points']) . " ORDER BY min_points DESC ";
        }
        $sql = "SELECT rank_name FROM " . $ecs->table('user_rank') . $where;
        $user['rank_name'] = $db->getOne($sql);

        $smarty->assign('user', $user);

        // 地址信息
        $sql = "SELECT * FROM " . $ecs->table('user_address') . " WHERE user_id = '$order[user_id]'";
        $smarty->assign('address_list', $db->getAll($sql));
    }

    /* 取得订单商品及货品 */
    $goods_list = array();
    $goods_attr = array();
    $sql = "SELECT o.*, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name
            FROM " . $ecs->table('order_goods') . " AS o
                LEFT JOIN " . $ecs->table('goods') . " AS g
                    ON o.goods_id = g.goods_id
                LEFT JOIN " . $ecs->table('brand') . " AS b
                    ON g.brand_id = b.brand_id
            WHERE o.order_id = '$order[order_id]'";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {

        $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
        $row['formated_goods_price']    = price_format($row['goods_price']);

        $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

        if ($row['extension_code'] == 'package_buy')
        {
            $row['storage'] = '';
            $row['brand_name'] = '';
            $row['package_goods_list'] = get_package_goods($row['goods_id']);
        }

        $goods_list[] = $row;
    }

    $attr = array();
    $arr  = array();
    foreach ($goods_attr AS $index => $array_val)
    {
        foreach ($array_val AS $value)
        {
            $arr = explode(':', $value);//以 : 号将属性拆开
            $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
        }
    }

    $smarty->assign('goods_attr', $attr);
    $smarty->assign('goods_list', $goods_list);

    /* 取得能执行的操作列表 */
    $operable_list = operable_list($order);
    $smarty->assign('operable_list', $operable_list);

    /* 取得订单操作记录 */
    $act_list = array();
    $sql = "SELECT * FROM " . $ecs->table('order_action') . " WHERE order_id = '$order[order_id]' ORDER BY log_time DESC,action_id DESC";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $row['order_status']    = $_LANG['os'][$row['order_status']];
        $row['pay_status']      = $_LANG['ps'][$row['pay_status']];
        $row['shipping_status'] = $_LANG['ss'][$row['shipping_status']];
        $row['action_time']     = local_date($_CFG['time_format'], $row['log_time']);
        $act_list[] = $row;
    }
    $smarty->assign('action_list', $act_list);

    /* 取得是否存在实体商品 */
    $smarty->assign('exist_real_goods', exist_real_goods($order['order_id']));

    /* 是否打印订单，分别赋值 */
    if (isset($_GET['print']))
    {
        $smarty->assign('shop_name',    $_CFG['shop_name']);
        $smarty->assign('shop_url',     $ecs->url());
        $smarty->assign('shop_address', $_CFG['shop_address']);
        $smarty->assign('service_phone',$_CFG['service_phone']);
        $smarty->assign('print_time',   local_date($_CFG['time_format']));
        $smarty->assign('action_user',  $_SESSION['admin_name']);

        $smarty->display('order_print.htm');
    }
    /* 打印快递单 */
    elseif (isset($_GET['shipping_print']))
    {
        //$smarty->assign('print_time',   local_date($_CFG['time_format']));
        //发货地址所在地
        $region_array = array();
        $region_id = !empty($_CFG['shop_country']) ? $_CFG['shop_country'] . ',' : '';
        $region_id .= !empty($_CFG['shop_province']) ? $_CFG['shop_province'] . ',' : '';
        $region_id .= !empty($_CFG['shop_city']) ? $_CFG['shop_city'] . ',' : '';
        $region_id .= $order['country'].','.$order['province'].','.$order['city'].','.$order['district'].',';
        $region_id = substr($region_id, 0, -1);
        $region = $db->getAll("SELECT region_id, region_name FROM " . $ecs->table("region") . " WHERE region_id IN ($region_id)");
        if (!empty($region))
        {
            foreach($region as $region_data)
            {
                $region_array[$region_data['region_id']] = $region_data['region_name'];
            }
        }
        $smarty->assign('shop_name',    $_CFG['shop_name']);
        $smarty->assign('order_id',    $order_id);
        $smarty->assign('province', $region_array[$_CFG['shop_province']]);
        $smarty->assign('city', $region_array[$_CFG['shop_city']]);
        $smarty->assign('shop_address', $_CFG['shop_address']);
        $smarty->assign('service_phone',$_CFG['service_phone']);
        $shipping = $db->getRow("SELECT * FROM " . $ecs->table("shipping") . " WHERE shipping_id = " . $order['shipping_id']);
        /* 取快递单背景宽高 */
        $shipping['print_bg_size'] = array('width' => '800', 'height' => '467');
        /* 设置打印模板 */
        if($order['agency_id'] == 1 && $order['pay_id'] != 3) $bg_type = 1; // 广东省在线支付方式
        elseif($order['agency_id'] == 1 && $order['pay_id'] == 3) $bg_type = 2; // 广东省到付方式
        elseif($order['pay_id'] != 3) $bg_type = 3;// 杭州仓在线支付方式
        elseif($order['pay_id'] == 3) $bg_type = 4;// 杭州仓到付方式
        if($bg_type == 1){
            $shipping['print_bg']='http://www.eggms.com/images/receipt/dly_kaidi_2.jpg';
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,131,161,b_shop_province||,||t_customer_province,收件人-省份,63,21,498,158,b_customer_province||,||t_shop_address,网店-地址,184,21,130,207,b_shop_address||,||t_shop_name,网店-名称,180,21,134,87,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,179,236,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,648,240,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,600,240,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,506,92,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,461,195,b_customer_address||,||t_months,月-当日日期,39,21,200,385,b_months||,||t_day,日-当日日期,28,21,238,385,b_day||,||t_shop_city,网店-城市,65,21,215,161,b_shop_city||,||t_shop_district,网店-区/县,68,21,304,158,b_shop_district||,||t_customer_city,收件人-城市,63,21,590,157,b_customer_city||,||t_customer_district,收件人-区/县,70,21,672,157,b_customer_district||,||t_shipping_fee,邮费已收,134,21,690,310,t_shipping_fee||,||t_year,年-当日日期,47,21,145,385,b_year||,||";
        }elseif($bg_type == 2){
            $shipping['print_bg']='http://www.eggms.com/images/receipt/dly_kaidi_1.jpg';
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,129,192,b_shop_province||,||t_customer_province,收件人-省份,63,21,422,188,b_customer_province||,||t_shop_address,网店-地址,184,21,128,231,b_shop_address||,||t_shop_name,网店-名称,180,21,183,141,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,248,110,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,573,135,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,573,93,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,423,93,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,394,220,b_customer_address||,||t_months,月-当日日期,27,21,359,316,b_months||,||t_day,日-当日日期,28,21,391,316,b_day||,||t_shop_city,网店-城市,65,21,197,192,b_shop_city||,||t_shop_district,网店-区/县,68,21,273,191,b_shop_district||,||t_customer_city,收件人-城市,63,21,500,186,b_customer_city||,||t_customer_district,收件人-区/县,96,21,573,186,b_customer_district||,||t_pigeon,√-对号,21,21,320,373,b_pigeon||,||t_total_fee,小写金额,99,21,742,359,t_total_fee||,||t_shipping_fee,邮费已收,99,21,728,400,t_shipping_fee||,||t_year,年-当日日期,47,21,308,316,b_year||,||";
        }elseif($bg_type == 3){
            $shipping['print_bg']='http://www.eggms.com/images/receipt/dly_kaidi_2.jpg';
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,131,161,b_shop_province||,||t_customer_province,收件人-省份,63,21,498,158,b_customer_province||,||t_shop_address,网店-地址,184,21,130,207,b_shop_address||,||t_shop_name,网店-名称,180,21,134,87,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,179,236,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,648,231,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,600,231,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,506,92,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,461,195,b_customer_address||,||t_months,月-当日日期,39,21,200,385,b_months||,||t_day,日-当日日期,28,21,238,385,b_day||,||t_shop_city,网店-城市,65,21,215,161,b_shop_city||,||t_shop_district,网店-区/县,68,21,304,158,b_shop_district||,||t_customer_city,收件人-城市,63,21,590,157,b_customer_city||,||t_customer_district,收件人-区/县,70,21,672,157,b_customer_district||,||t_shipping_fee,邮费已收,134,21,690,310,t_shipping_fee||,||t_year,年-当日日期,47,21,145,385,b_year||,||";
        }elseif($bg_type == 4){
            $shipping['print_bg']='/Public/images/kaidi_3.jpg';
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,161,141,b_shop_province||,||t_customer_province,收件人-省份,63,21,478,128,b_customer_province||,||t_shop_address,网店-地址,184,21,160,187,b_shop_address||,||t_shop_name,网店-名称,180,21,134,87,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,179,200,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,648,200,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,600,200,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,506,62,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,426,165,b_customer_address||,||t_months,月-当日日期,39,21,180,385,b_months||,||t_day,日-当日日期,28,21,218,385,b_day||,||t_shop_city,网店-城市,65,21,245,141,b_shop_city||,||t_shop_district,网店-区/县,68,21,334,138,b_shop_district||,||t_customer_city,收件人-城市,63,21,570,127,b_customer_city||,||t_customer_district,收件人-区/县,70,21,652,127,b_customer_district||,||t_pigeon,√-对号,21,21,530,223,b_pigeon||,||t_total_fee,小写金额,99,21,470,335,t_total_fee||,||t_shipping_fee,邮费已收,99,21,680,354,t_shipping_fee||,||t_year,年-当日日期,47,21,125,385,b_year||,||";
        }elseif($bg_type == 5){
            $shipping['print_bg']='http://www.eggms.com/images/receipt/dly_kaidi_2.jpg';
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,131,161,b_shop_province||,||t_customer_province,收件人-省份,63,21,498,158,b_customer_province||,||t_shop_address,网店-地址,184,21,130,207,b_shop_address||,||t_shop_name,网店-名称,180,21,134,87,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,179,236,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,648,240,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,600,240,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,506,92,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,461,195,b_customer_address||,||t_months,月-当日日期,39,21,200,385,b_months||,||t_day,日-当日日期,28,21,238,385,b_day||,||t_shop_city,网店-城市,65,21,215,161,b_shop_city||,||t_shop_district,网店-区/县,68,21,304,158,b_shop_district||,||t_customer_city,收件人-城市,63,21,590,157,b_customer_city||,||t_customer_district,收件人-区/县,70,21,672,157,b_customer_district||,||t_shipping_fee,邮费已收,134,21,690,310,t_shipping_fee||,||t_year,年-当日日期,47,21,145,385,b_year||,||";
        }elseif($bg_type == 6){
            $shipping['print_bg']='/Public/images/kaidi_2.jpg';
            $shipping['config_lable'] = "t_shop_province,网店-省份,63,21,129,192,b_shop_province||,||t_customer_province,收件人-省份,63,21,422,188,b_customer_province||,||t_shop_address,网店-地址,184,21,128,231,b_shop_address||,||t_shop_name,网店-名称,180,21,183,141,b_shop_name||,||t_shop_tel,网店-联系电话,133,21,248,110,b_shop_tel||,||t_customer_tel,收件人-电话,135,21,573,135,b_customer_tel||,||t_customer_mobel,收件人-手机,134,21,573,103,b_customer_mobel||,||t_customer_name,收件人-姓名,91,21,423,112,b_customer_name||,||t_customer_address,收件人-详细地址,318,21,394,220,b_customer_address||,||t_months,月-当日日期,27,21,359,316,b_months||,||t_day,日-当日日期,28,21,391,316,b_day||,||t_shop_city,网店-城市,65,21,197,192,b_shop_city||,||t_shop_district,网店-区/县,68,21,273,191,b_shop_district||,||t_customer_city,收件人-城市,63,21,500,186,b_customer_city||,||t_customer_district,收件人-区/县,96,21,573,186,b_customer_district||,||t_pigeon,√-对号,21,21,520,383,b_pigeon||,||t_total_fee,小写金额,99,21,732,349,t_total_fee||,||t_shipping_fee,邮费已收,99,21,728,384,t_shipping_fee||,||t_year,年-当日日期,47,21,308,316,b_year||,||";
        }


        //打印单模式
        if ($shipping['print_model'] == 2)
        {

            /* 取快递单背景宽高 */
            $shipping['print_bg_size'] = array('width' => '800', 'height' => '467');
            /* 标签信息 */
            $lable_box = array();
            $lable_box['t_shop_country'] = $region_array[$_CFG['shop_country']]; //网店-国家
            $lable_box['t_shop_city'] = $region_array[$_CFG['shop_city']]; //网店-城市
            $lable_box['t_shop_province'] = $region_array[$_CFG['shop_province']]; //网店-省份
            $lable_box['t_shop_name'] = $_CFG['shop_name']; //网店-名称
            $lable_box['t_shop_district'] = ''; //网店-区/县
            $lable_box['t_shop_tel'] = $_CFG['service_phone']; //网店-联系电话
            $lable_box['t_shop_address'] = $_CFG['shop_address']; //网店-地址
            $lable_box['t_customer_country'] = $region_array[$order['country']]; //收件人-国家
            $lable_box['t_customer_province'] = $region_array[$order['province']]; //收件人-省份
            $lable_box['t_customer_city'] = $region_array[$order['city']]; //收件人-城市
            $lable_box['t_customer_district'] = $region_array[$order['district']]; //收件人-区/县
            $lable_box['t_customer_tel'] = $order['tel']; //收件人-电话
            $lable_box['t_customer_mobel'] = $order['mobile']; //收件人-手机
            $lable_box['t_customer_post'] = $order['zipcode']; //收件人-邮编
            $lable_box['t_customer_address'] = $order['address']; //收件人-详细地址
            $lable_box['t_customer_name'] = $order['consignee']; //收件人-姓名
            $lable_box['t_total_fee_cny'] = cny(round($order['order_amounts'],1)); //代收费用
            $lable_box['t_total_fee'] = $order['order_amounts']; //代收费用
            $gmtime_utc_temp = gmtime(); //获取 UTC 时间戳
            $lable_box['t_year'] = date('Y', $gmtime_utc_temp); //年-当日日期
            $lable_box['t_months'] = date('m', $gmtime_utc_temp); //月-当日日期
            $lable_box['t_day'] = date('d', $gmtime_utc_temp); //日-当日日期

            $lable_box['t_order_no'] = $order['order_sn']; //订单号-订单
            $lable_box['t_order_postscript'] = $order['postscript']; //备注-订单
            $lable_box['t_order_best_time'] = $order['best_time']; //送货时间-订单
            $lable_box['t_pigeon'] = '√'; //√-对号
            $lable_box['t_custom_content'] = ''; //自定义内容

            //标签替换
            $temp_config_lable = explode('||,||', $shipping['config_lable']);
            if (!is_array($temp_config_lable))
            {
                $temp_config_lable[] = $shipping['config_lable'];
            }
            foreach ($temp_config_lable as $temp_key => $temp_lable)
            {
                $temp_info = explode(',', $temp_lable);
                if (is_array($temp_info))
                {
                    $temp_info[1] = $lable_box[$temp_info[0]];
                }
                $temp_config_lable[$temp_key] = implode(',', $temp_info);
            }
            $shipping['config_lable'] = implode('||,||',  $temp_config_lable);

            $smarty->assign('shipping', $shipping);

            $smarty->display('print.htm');
        }
        elseif (!empty($shipping['shipping_print']))
        {
            /* 代码 */
            echo $smarty->fetch("str:" . $shipping['shipping_print']);
        }
        else
        {
            $shipping_code = $db->getOne("SELECT shipping_code FROM " . $ecs->table('shipping') . " WHERE shipping_id=" . $order['shipping_id']);
            if ($shipping_code)
            {
                include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping_code . '.php');
            }

            if (!empty($_LANG['shipping_print']))
            {
                echo $smarty->fetch("str:$_LANG[shipping_print]");
            }
            else
            {
                echo $_LANG['no_print_shipping'];
            }
        }
    }
    else
    {
        /* 模板赋值 */
        $smarty->assign('ur_here', $_LANG['order_info']);
        $smarty->assign('action_link', array('href' => 'order.php?act=list&' . list_link_postfix(), 'text' => $_LANG['02_order_list']));

        /* 显示模板 */
        assign_query_info();
        $smarty->display('order_info.htm');
    }
}


/*------------------------------------------------------ */
//-- 修改订单（处理提交）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'step_post')
{
    /* 检查权限 */
    admin_priv('order_edit');

    /* 取得参数 step */
    $step_list = array('user', 'edit_goods', 'add_goods', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money', 'invoice');
    $step = isset($_REQUEST['step']) && in_array($_REQUEST['step'], $step_list) ? $_REQUEST['step'] : 'user';

    /* 取得参数 order_id */
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
    if ($order_id > 0)
    {
        $old_order = order_info($order_id);
    }

    /* 取得参数 step_act 添加还是编辑 */
    $step_act = isset($_REQUEST['step_act']) ? $_REQUEST['step_act'] : 'add';

    $consignee['province']=$_REQUEST['province'];
    $consignee['city']=$_REQUEST['city'];
    $consignee['district']=$_REQUEST['district'];
    $daodansong_id=!empty($_REQUEST['daodansong_id'])?$_REQUEST['daodansong_id']:"0";
    $order_area_id=is_buy($consignee);//判断改区域能否购买
    $agency_id=empty($order_area_id)?404:$order_area_id;
    /* 插入订单信息 */
    if ('user' == $step)
    {
        /* 取得参数：user_id */
        $user_id = ($_POST['anonymous'] == 1) ? 0 : intval($_POST['user']);
        if(!$_REQUEST['payment']){
          echo   "没有选择支付方式";
            exit();
        }


        $sql="SELECT pay_name FROM ".$GLOBALS['ecs']->table('payment') ."WHERE pay_id=".$_REQUEST['payment'];
        $pay_name=$db->getOne($sql);
        $from_ad=$_POST['from_ad']?intval($_POST['from_ad']):0;
        switch ($from_ad) {
            case '0':
                $referer="本站";  
            case '1':
                $referer="淘宝订单";
                break;
            case '2':
                $referer="客服商城订单";
                break;
            case '3':
               $referer="老师优惠订单";
            case '5':
               $referer="补发订单";
                break;
        }
        /* 插入新订单，状态为无效 */
        $order = array(
            'user_id'           => $user_id,
            'add_time'          => gmtime(),
            'order_status'      => OS_INVALID,
            'shipping_status'   => SS_UNSHIPPED,
            'pay_status'        => PS_UNPAYED,
            'from_ad'           => $from_ad,
            'referer'           => $referer,
            'consignee'         => $_REQUEST['consignee'],
            'country'           => $_REQUEST['country'],
            'province'          => $_REQUEST['province'],
            'city'              => $_REQUEST['city'],
            'district'          => $_REQUEST['district'],
            'mobile'            => $_REQUEST['mobile'],
            'address'           => $_REQUEST['address'],
            'pay_id'            => $_REQUEST['payment'],
            'pay_name'          => $pay_name, 
            'shipping_id'       => '13',
            'shipping_name'     => '速递',
            'agency_id'         => $agency_id,
            'daodansong_id'     => $daodansong_id
        );

        do
        {
            $order['order_sn'] = get_order_sn();
            if ($db->autoExecute($ecs->table('order_info'), $order, 'INSERT', '', 'SILENT'))
            {
                break;
            }
            else
            {
                if ($db->errno() != 1062)
                {
                    die($db->error());
                }
            }
        }
        while (true); // 防止订单号重复

        $order_id = $db->insert_id();
        $_SESSION['order_id']=$order_id;
        /* todo 记录日志 */
        admin_log($order['order_sn'], 'add', 'order');

        /* 插入 pay_log */
        $sql = 'INSERT INTO ' . $ecs->table('pay_log') . " (order_id, order_amount, order_type, is_paid)" .
                " VALUES ('$order_id', 0, '" . PAY_ORDER . "', 0)";
        $db->query($sql);

        /* 下一步 */
        ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
        exit;
    }
    /* 编辑商品信息 */
    elseif ('edit_goods' == $step)
    {   
        $order=order_info($order_id);   
        $area_id=$order['agency_id'];
        if (isset($_POST['rec_id']))
        {   
            //如果是编辑订单则比较修改库存
            if($_REQUEST['step_act']=='edit'){
                //获取订单商品
                $sql="SELECT rec_id,goods_sku,goods_attr_sku,compose_note,goods_number ,goods_name,goods_attr".
                    " FROM ".$GLOBALS['ecs']->table('order_goods').
                    " WHERE order_id = $order_id ";
                $order_goods=$db->getAll($sql);
                foreach($_POST['rec_id'] AS $key => $rec_id){
                        $goods_number = intval($_POST['goods_number'][$key]);
                        foreach ($order_goods as $k => $value) {
                            if($value['rec_id']==$rec_id){
                                $order_goods[$k]['goods_number']=$goods_number-$value['goods_number'];
                            }
                           if($order_goods[$k]['goods_number']==0){
                            $order_goods[$k]="";
                           }

                        }
                }
                $order_goods=array_filter($order_goods);//去除数组空值
                //如果有更新商品数量则减少库存
                if($order_goods){
                    //循环重组订单商品
                    foreach ($order_goods as $key => $value) {
                        if($value['goods_attr_sku']){
                            $goods[$value['goods_attr_sku']]=$value['goods_number'];
                        }
                        else{
                            $goods[$value['goods_sku']]=$value['goods_number'];
                        }
                    }


                    //查询判断库存是否大于订单商品
                    foreach ($goods as $sku => $number) {
                        if($number>0){
                            $sql="SELECT goods_number FROM".$GLOBALS['ecs']->table('goods_stock').
                                 " WHERE area_id=$area_id AND goods_sku=$sku";
                            $stock=$db->getOne($sql);
                            // 如果商品增加则判断库存是否足够
                            if($stock<$number){
                                $links[] = array('href' => 'order.php?act=edit&order_id='.$order_id.'&step=goods' , 'text' => "商品编号为".$sku.'的商品库存不足点击后退键返回');
                                    sys_msg("商品编号为".$sku.'的商品库存不足点击后退键返回', 100, $links);
                                // echo  "商品编号为".$sku.'的商品库存不足点击后退键返回';
                                exit();
                            }
                        }
                    }
                    //循环商品减少库存
                    foreach ($goods as $sku => $number) {
                        if($number>0){
                            change_goods_storage($sku,3,-$number);//减少库存
                        }
                        if ($number<0) {
                            change_goods_storage($sku,3,abs($number));//减少库存
                        }
                    }

                }
            }
            foreach ($_POST['rec_id'] AS $key => $rec_id)
            {

                /* 取得参数 */
              $goods_price = floatval($_POST['goods_price'][$key]);
              $goods_number = intval($_POST['goods_number'][$key]);
                /* 修改 */
                $sql = "UPDATE " . $ecs->table('order_goods') .
                        " SET goods_price = '$goods_price', " .
                        "goods_number = '$goods_number' " .
                        "WHERE rec_id = '$rec_id' LIMIT 1";
                $db->query($sql);
            }

            /* 更新商品总金额和订单总金额 */
            $goods_amount = order_amount($order_id);
            update_order($order_id, array('goods_amount' => $goods_amount));
            update_order_amount($order_id);

            /* 更新 pay_log */
            update_pay_log($order_id);

            /* todo 记录日志 */
            $sn = $old_order['order_sn'];
            $new_order = order_info($order_id);
            if ($old_order['total_fee'] != $new_order['total_fee'])
            {
                $sn .= ',' . sprintf($_LANG['order_amount_change'], $old_order['total_fee'], $new_order['total_fee']);
            }
            admin_log($sn, 'edit', 'order');
        }

        /* 跳回订单商品 */
        ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
        exit;
    }
    /* 添加商品 */
    elseif ('add_goods' == $step)
    {       $order = order_info($order_id);
            $agency_id=$order['agency_id'];//办事处ID
            include_once(ROOT_PATH . 'includes/cls_json.php');
            $json = new JSON();
            $goods_info  = $json->decode($_REQUEST['goods_info']);
            $attr = $json->decode($_REQUEST['attr']);

            /* 取得参数 */
            $goods_id = $goods_info->goods_id;
            $sql = "SELECT goods_sku FROM ".$ecs->table('goods') ."WHERE goods_id = $goods_id";
            $sku = $db->getOne($sql);
            $goods_price = $goods_info->goods_price;
            $goods_number=$goods_info->goods_number;//商品数量


            //如果是编辑状态则减少库存  库存不足提交错误
        if($_REQUEST['step_act']=='edit'){

                if($attr){
                    foreach ($attr as $key => $value) {
                            $goods[$key]=$value;
                    }
                }
                else{
                    $goods[$sku]=$goods_number;
                }
                //查询判断库存是否大于订单商品
                foreach ($goods as $sku => $number) {
                    $sql="SELECT goods_number FROM".$GLOBALS['ecs']->table('goods_stock').
                         " WHERE area_id=$agency_id AND goods_sku=$sku";
                    $stock=$db->getOne($sql);
                    if($stock<$number){
                        $return['error']=0;
                        $return['content']="商品编号为".$sku.'的商品库存不足';
                        die($json->encode($return));
                        exit();
                    }
                }
                //循环商品减少库存
                foreach ($goods as $sku => $number) {
                    change_goods_storage($sku,3,-$number);
                }
        }
        if($attr)
        {   //插入有属性的普通商品
                foreach ($attr as $key => $value) {
                    if($value){
                        //查询属性信息
                        $sql="SELECT attr_value,goods_attr_id,attr_sku ".
                         'FROM ' . $GLOBALS['ecs']->table('goods_attr') .
                         " WHERE attr_sku =$key";
                         $attr_info=$db->getRow($sql);
                         //判断订单中是否有该商品
                        $sql ="SELECT goods_number FROM " . $ecs->table('order_goods') ." WHERE order_id='$order_id' AND goods_attr_sku = '$key'";
                        $there_attr=$db->getOne($sql);
                        if($there_attr){
                             $sql="UPDATE ".$GLOBALS['ecs']->table('order_goods').
                             " set goods_number=(goods_number+$value) , goods_price='$goods_price'".
                             " WHERE order_id='$order_id' AND goods_attr_sku = '$key'";
                             $db->query($sql);
                         }
                         else{
                                $sql = "INSERT INTO " . $ecs->table('order_goods') .
                                "(order_id, goods_id, goods_name, goods_sku, goods_number, market_price, " .
                                "goods_price, goods_attr, extension_code, parent_id, is_gift, goods_attr_id,goods_attr_sku) " .
                                "SELECT '$order_id', goods_id, goods_name, goods_sku, ".
                                "'$value', market_price, '$goods_price', '" .$attr_info['attr_value'] . "', " .
                                "extension_code, 0, 0 , '".$attr_info['goods_attr_id']."','".$attr_info['attr_sku']."' " .
                                "FROM " . $ecs->table('goods') .
                                " WHERE goods_id = '$goods_id' LIMIT 1";
                                $db->query($sql);

                         }
                    }
                }
        }
        else
        {   
            // 查询订单是否有改商品有则修改数量
            $sql ="SELECT goods_number FROM " . $ecs->table('order_goods') ." WHERE order_id='$order_id' AND goods_id = '$goods_id' AND extension_code =''  ";
            $there=$db->getOne($sql);
            // 如果存在商品
            if($there){
               $sql="UPDATE ".$GLOBALS['ecs']->table('order_goods').
             " set goods_number=(goods_number+$goods_number) , goods_price='$goods_price'".
             " WHERE order_id='$order_id' AND goods_id = '$goods_id'";
             $db->query($sql);
            }
            else{
                //不存在商品则插入普通商品
                $sql = "INSERT INTO " . $ecs->table('order_goods') .
                    " (order_id, goods_id, goods_name, goods_sku, " .
                    "goods_number, market_price, goods_price,  " .
                    "extension_code, parent_id, is_gift,add_time)" .
                "SELECT '$order_id', goods_id, goods_name, goods_sku, " .
                    "'$goods_number', market_price, '$goods_price', " .
                    "extension_code, 0, 0,'".time()."'" .
                "FROM " . $ecs->table('goods') .
                " WHERE goods_id = '$goods_id' LIMIT 1";
                $db->query($sql);
            }

        }
        /* 更新商品总金额和订单总金额 */
        update_order($order_id, array('goods_amount' => order_amount($order_id)));
        update_order_amount($order_id);
        /* 更新 pay_log */
        update_pay_log($order_id);

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        $new_order = order_info($order_id);
        if ($old_order['total_fee'] != $new_order['total_fee'])
        {
            $sn .= ',' . sprintf($_LANG['order_amount_change'], $old_order['total_fee'], $new_order['total_fee']);
        }
        admin_log($sn, 'edit', 'order');
        // //插入成功后返回处理
        /* 取得订单商品 */
        $sql = "SELECT o.rec_id, o.goods_id, o.goods_name,o.goods_attr_sku,o.compose_note, o.goods_sku, o.market_price, o.goods_number, g.goods_weight, gs.goods_number AS goods_stock, " .
            "o.goods_price, o.goods_attr, o.is_real, o.parent_id, o.is_gift, g.give_integral, " .
            "o.goods_price * o.goods_number AS subtotal, o.extension_code " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " o ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = o.goods_id " .
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON gs.goods_id = o.goods_id AND gs.goods_attr_id = o.goods_attr_id AND gs.area_id = $agency_id" .
            " WHERE o.order_id = '$order_id'";
        $goods_list = $db->getAll($sql);
        if (!empty($goods_list))
        {
            foreach ($goods_list AS $key => $value)
            {
                /*读取内存库存*/
                $value['goods_stock'] = empty($value['goods_attr_sku'])?$GLOBALS['virtualStock']->selectStock($value['goods_sku']):$GLOBALS['virtualStock']->selectStock($value['goods_attr_sku']);
                $goods_list_b[$key+1]=$value;
                $count=$value['goods_number']+$count;
                $weight=$value['goods_weight']+$weight;
            }
            $goods_list=$goods_list_b;
        }
        $smarty->assign('count', $count);
        $smarty->assign('goods_list', $goods_list);
        $smarty->assign('order_id', $order['order_id']);
        $smarty->assign('from_ad', $order['from_ad']);
        //  $smarty->assign('goods', $goods_list);
        /*获取商品运费*/
        //判断订单中是否有免邮商品
        $sql="SELECT is_shipping FROM ".$GLOBALS['ecs']->table('goods') ." AS g ".
             " LEFT JOIN ".$GLOBALS['ecs']->table('order_goods')."AS o ".
             " ON g.goods_id = o.goods_id ".
             " WHERE o.order_id=$order_id AND is_shipping=1";
        $is_shipping=$db->getOne($sql);
        /*获取商品运费*/
        $shipping_fee=shipping_fee(order_amount($order_id),$order['pay_id'],$is_shipping,'0',$order,$weight,$order['user_id']);
        $smarty->assign('shipping_fee', $shipping_fee);
        /* 取得商品总金额 */
        $smarty->assign('goods_amount', order_amount($order_id));
        /*应支付金额*/
        $pay_fee=order_amount($order_id)+$shipping_fee;
        $smarty->assign('pay_fee', $pay_fee);
        /*查询订单是否已支付了金额*/
        $sql="SELECT order_amount FROM ".$GLOBALS['ecs']->table('pay_log') .
             "WHERE order_id=$order_id AND is_paid = 1";
        $paid=$db->getOne($sql);
        if($paid){
             $order=order_info($order_id);
             $smarty->assign('paid',$order['money_paid']);//已支付金额
             $smarty->assign('pay',$order['order_amount']);//待支付金额
        }
         $smarty->assign('step_act', $_REQUEST['step_act']);
         $return['error']   = 1; 
         $return['content'] = $smarty->fetch("order/order_goods_list.htm");
         echo $json->encode($return);
        exit();
    }
    /* 商品 */
    elseif ('goods' == $step)
    {
        /* 下一步 */
        if (isset($_POST['next']))
        {
            ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=consignee\n");
            exit;
        }
        /* 完成 */
        elseif (isset($_POST['finish']))
        {
            /* 初始化提示信息和链接 */
            $msgs   = array();
            $links  = array();

            /* 如果已付款，检查金额是否变动，并执行相应操作 */
            $order = order_info($order_id);
            handle_order_money_change($order, $msgs, $links);

            /* 显示提示信息 */
            if (!empty($msgs))
            {
                sys_msg(join(chr(13), $msgs), 0, $links);
            }
            else
            {
                /* 跳转到订单详情 */
                ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
                exit;
            }
        }
    }
    /* 保存收货人信息 */
    elseif ('consignee' == $step)
    {
        /* 保存订单 */
        $order = $_POST;
        update_order($order_id, $order);

        /* 该订单所属办事处是否变化 */
        // $agency_changed = $old_order['agency_id'] != $order['agency_id'];

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        admin_log($sn, 'edit', 'order');

        if (isset($_POST['next']))
        {
            /* 下一步 */
            if (exist_real_goods($order_id))
            {
                /* 存在实体商品，去配送方式 */
                ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=shipping\n");
                exit;
            }
            else
            {
                /* 不存在实体商品，去支付方式 */
                ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=payment\n");
                exit;
            }
        }
        elseif (isset($_POST['finish']))
        {
            /* 如果是编辑且存在实体商品，检查收货人地区的改变是否影响原来选的配送 */
            if ('edit' == $step_act && exist_real_goods($order_id))
            {
                $order = order_info($order_id);

                /* 取得可用配送方式 */
                $region_id_list = array(
                    $order['country'], $order['province'], $order['city'], $order['district']
                );
                $shipping_list = available_shipping_list($region_id_list);

                // /* 判断订单的配送是否在可用配送之内 */
                // $exist = false;
                // foreach ($shipping_list AS $shipping)
                // {
                //     if ($shipping['shipping_id'] == $order['shipping_id'])
                //     {
                //         $exist = true;
                //         break;
                //     }
                // }

                // /* 如果不在可用配送之内，提示用户去修改配送 */
                // if (!$exist)
                // {
                //     // 修改配送为空，配送费和保价费为0
                //     update_order($order_id, array('shipping_id' => 0, 'shipping_name' => ''));
                //     $links[] = array('text' => $_LANG['step']['shipping'], 'href' => 'order.php?act=edit&order_id=' . $order_id . '&step=shipping');
                //     sys_msg($_LANG['continue_shipping'], 1, $links);
                // }
            }

            /* 完成 */
            if ($agency_changed)
            {
                ecs_header("Location: order.php?act=list\n");
            }
            else
            {
                ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
            }
            exit;
        }
    }
    /* 保存配送信息 */
    elseif ('shipping' == $step)
    {
        /* 如果不存在实体商品，退出 */
        if (!exist_real_goods($order_id))
        {
            die ('Hacking Attemp');
        }

        /* 取得订单信息 */
        $order_info = order_info($order_id);
        $region_id_list = array($order_info['country'], $order_info['province'], $order_info['city'], $order_info['district']);

        /* 保存订单 */
        $shipping_id = $_POST['shipping'];
        $shipping = shipping_area_info($shipping_id, $region_id_list);
        $weight_amount = order_weight_price($order_id);
        $shipping_fee = shipping_fee($shipping['shipping_code'], $shipping['configure'], $weight_amount['weight'], $weight_amount['amount'], $weight_amount['number'], $order_info['user_id']);
        $order = array(
            'shipping_id' => $shipping_id,
            'shipping_name' => addslashes($shipping['shipping_name']),
            'shipping_fee' => $shipping_fee
        );

        if (isset($_POST['insure']))
        {
            /* 计算保价费 */
            $order['insure_fee'] = shipping_insure_fee($shipping['shipping_code'], order_amount($order_id), $shipping['insure']);
        }
        else
        {
            $order['insure_fee'] = 0;
        }
        update_order($order_id, $order);
        update_order_amount($order_id);

        /* 更新 pay_log */
        update_pay_log($order_id);

        /* 清除首页缓存：发货单查询 */
        clear_cache_files('index.dwt');

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        $new_order = order_info($order_id);
        if ($old_order['total_fee'] != $new_order['total_fee'])
        {
            $sn .= ',' . sprintf($_LANG['order_amount_change'], $old_order['total_fee'], $new_order['total_fee']);
        }
        admin_log($sn, 'edit', 'order');

        if (isset($_POST['next']))
        {
            /* 下一步 */
            ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=payment\n");
            exit;
        }
        elseif (isset($_POST['finish']))
        {
            /* 初始化提示信息和链接 */
            $msgs   = array();
            $links  = array();

            /* 如果已付款，检查金额是否变动，并执行相应操作 */
            $order = order_info($order_id);
            handle_order_money_change($order, $msgs, $links);

            /* 如果是编辑且配送不支持货到付款且原支付方式是货到付款 */
            if ('edit' == $step_act && $shipping['support_cod'] == 0)
            {
                $payment = payment_info($order['pay_id']);
                if ($payment['is_cod'] == 1)
                {
                    /* 修改支付为空 */
                    update_order($order_id, array('pay_id' => 0, 'pay_name' => ''));
                    $msgs[]     = $_LANG['continue_payment'];
                    $links[]    = array('text' => $_LANG['step']['payment'], 'href' => 'order.php?act=' . $step_act . '&order_id=' . $order_id . '&step=payment');
                }
            }

            /* 显示提示信息 */
            if (!empty($msgs))
            {
                sys_msg(join(chr(13), $msgs), 0, $links);
            }
            else
            {
                /* 完成 */
                ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
                exit;
            }
        }
    }
    /* 保存支付信息 */
    elseif ('payment' == $step)
    {
        /* 取得支付信息 */
        $pay_id = $_POST['payment'];
        $payment = payment_info($pay_id);

        /* 计算支付费用 */
        $order_amount = order_amount($order_id);
        if ($payment['is_cod'] == 1)
        {
            $order = order_info($order_id);
            $region_id_list = array(
                $order['country'], $order['province'], $order['city'], $order['district']
            );
            $shipping = shipping_area_info($order['shipping_id'], $region_id_list);
            $pay_fee = pay_fee($pay_id, $order_amount, $shipping['pay_fee']);
        }
        else
        {
            $pay_fee = pay_fee($pay_id, $order_amount);
        }

        /* 保存订单 */
        $order = array(
            'pay_id' => $pay_id,
            'pay_name' => addslashes($payment['pay_name']),
            'pay_fee' => $pay_fee
        );
        update_order($order_id, $order);
        update_order_amount($order_id);

        /* 更新 pay_log */
        update_pay_log($order_id);

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        $new_order = order_info($order_id);
        if ($old_order['total_fee'] != $new_order['total_fee'])
        {
            $sn .= ',' . sprintf($_LANG['order_amount_change'], $old_order['total_fee'], $new_order['total_fee']);
        }
        admin_log($sn, 'edit', 'order');

        if (isset($_POST['next']))
        {
            /* 下一步 */
            ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=other\n");
            exit;
        }
        elseif (isset($_POST['finish']))
        {
            /* 初始化提示信息和链接 */
            $msgs   = array();
            $links  = array();

            /* 如果已付款，检查金额是否变动，并执行相应操作 */
            $order = order_info($order_id);
            handle_order_money_change($order, $msgs, $links);

            /* 显示提示信息 */
            if (!empty($msgs))
            {
                sys_msg(join(chr(13), $msgs), 0, $links);
            }
            else
            {
                /* 完成 */
                ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
                exit;
            }
        }
    }
    elseif ('other' == $step)
    {
        /* 保存订单 */
        $order = array();
        if (isset($_POST['pack']) && $_POST['pack'] > 0)
        {
            $pack               = pack_info($_POST['pack']);
            $order['pack_id']   = $pack['pack_id'];
            $order['pack_name'] = addslashes($pack['pack_name']);
        }
        else
        {
            $order['pack_id']   = 0;
            $order['pack_name'] = '';
        }
        if (isset($_POST['card']) && $_POST['card'] > 0)
        {
            $card               = card_info($_POST['card']);
            $order['card_id']   = $card['card_id'];
            $order['card_name'] = addslashes($card['card_name']);
            $order['card_fee']  = $card['card_fee'];
            $order['card_message'] = $_POST['card_message'];
        }
        else
        {
            $order['card_id']   = 0;
            $order['card_name'] = '';
            $order['card_fee']  = 0;
            $order['card_message'] = '';
        }
        $order['inv_type']      = $_POST['inv_type'];
        $order['inv_payee']     = $_POST['inv_payee'];
        $order['inv_content']   = $_POST['inv_content'];
        $order['how_oos']       = $_POST['how_oos'];
        $order['postscript']    = $_POST['postscript'];
        $order['to_buyer']      = $_POST['to_buyer'];
        update_order($order_id, $order);
        update_order_amount($order_id);

        /* 更新 pay_log */
        update_pay_log($order_id);

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        admin_log($sn, 'edit', 'order');

        if (isset($_POST['next']))
        {
            /* 下一步 */
            ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=money\n");
            exit;
        }
        elseif (isset($_POST['finish']))
        {
            /* 完成 */
            ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
            exit;
        }
    }
    elseif ('money' == $step)
    {
        /* 取得订单信息 */
        $old_order = order_info($order_id);
        if ($old_order['user_id'] > 0)
        {
            /* 取得用户信息 */
            $user = user_info($old_order['user_id']);
        }

        /* 保存信息 */
        $order['goods_amount']  = $old_order['goods_amount'];
        $order['discount']      = isset($_POST['discount']) && floatval($_POST['discount']) >= 0 ? round(floatval($_POST['discount']), 2) : 0;
        $order['tax']           = round(floatval($_POST['tax']), 2);
        $order['shipping_fee']  = isset($_POST['shipping_fee']) && floatval($_POST['shipping_fee']) >= 0 ? round(floatval($_POST['shipping_fee']), 2) : 0;
        $order['insure_fee']    = isset($_POST['insure_fee']) && floatval($_POST['insure_fee']) >= 0 ? round(floatval($_POST['insure_fee']), 2) : 0;
        $order['pay_fee']       = floatval($_POST['pay_fee']) >= 0 ? round(floatval($_POST['pay_fee']), 2) : 0;
        $order['money_paid']    = $old_order['money_paid'];
        $order['surplus']       = 0;
        //$order['integral']      = 0;
        $order['integral']=intval($_POST['integral']) >= 0 ? intval($_POST['integral']) : 0;
        $order['integral_money']= 0;
        $order['bonus_id']      = 0;
        $order['bonus']         = 0;

        /* 计算待付款金额 */
        $order['order_amount']  = $order['goods_amount'] - $order['discount']
                                + $order['tax']
                                + $order['shipping_fee']
                                + $order['insure_fee']
                                + $order['pay_fee']
                                - $order['money_paid'];
        if ($order['order_amount'] > 0)
        {
            if ($old_order['user_id'] > 0)
            {
                /* 如果选择了红包，先使用红包支付 */
                if ($_POST['bonus_id'] > 0)
                {
                    /* todo 检查红包是否可用 */
                    $order['bonus_id']      = $_POST['bonus_id'];
                    $bonus                  = bonus_info($_POST['bonus_id']);
                    $order['bonus']         = $bonus['type_money'];

                    $order['order_amount']  -= $order['bonus'];
                }

                /* 使用红包之后待付款金额仍大于0 */
                if ($order['order_amount'] > 0)
                {
                    if($old_order['extension_code']!='exchange_goods')
                    {
                    /* 如果设置了积分，再使用积分支付 */
                       if (isset($_POST['integral']) && intval($_POST['integral']) > 0)
                         {
                           /* 检查积分是否足够 */
                           $order['integral']          = intval($_POST['integral']);
                           $order['integral_money']    = value_of_integral(intval($_POST['integral']));
                           if ($old_order['integral'] + $user['pay_points'] < $order['integral'])
                                {
                                   sys_msg($_LANG['pay_points_not_enough']);
                                }

                           $order['order_amount'] -= $order['integral_money'];
                         }
                    }
                    else
                    {
                      if (intval($_POST['integral']) > $user['pay_points']+$old_order['integral'])
                        {
                          sys_msg($_LANG['pay_points_not_enough']);
                        }

                    }
                    if ($order['order_amount'] > 0)
                    {
                        /* 如果设置了余额，再使用余额支付 */
                        if (isset($_POST['surplus']) && floatval($_POST['surplus']) >= 0)
                        {
                            /* 检查余额是否足够 */
                            $order['surplus'] = round(floatval($_POST['surplus']), 2);
                            if ($old_order['surplus'] + $user['user_money'] + $user['credit_line'] < $order['surplus'])
                            {
                                sys_msg($_LANG['user_money_not_enough']);
                            }

                            /* 如果红包和积分和余额足以支付，把待付款金额改为0，退回部分积分余额 */
                            $order['order_amount'] -= $order['surplus'];
                            if ($order['order_amount'] < 0)
                            {
                                $order['surplus']       += $order['order_amount'];
                                $order['order_amount']  = 0;
                            }
                        }
                    }
                    else
                    {
                        /* 如果红包和积分足以支付，把待付款金额改为0，退回部分积分 */
                        $order['integral_money']    += $order['order_amount'];
                        $order['integral']          = integral_of_value($order['integral_money']);
                        $order['order_amount']      = 0;
                    }
                }
                else
                {
                    /* 如果红包足以支付，把待付款金额设为0 */
                    $order['order_amount'] = 0;
                }
            }
        }

        update_order($order_id, $order);

        /* 更新 pay_log */
        update_pay_log($order_id);

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        $new_order = order_info($order_id);
        if ($old_order['total_fee'] != $new_order['total_fee'])
        {
            $sn .= ',' . sprintf($_LANG['order_amount_change'], $old_order['total_fee'], $new_order['total_fee']);
        }
        admin_log($sn, 'edit', 'order');

        /* 如果余额、积分、红包有变化，做相应更新 */
        if ($old_order['user_id'] > 0)
        {
            $user_money_change = $old_order['surplus'] - $order['surplus'];
            if ($user_money_change != 0)
            {
                log_account_change($user['user_id'], $user_money_change, 0, 0, 0, sprintf($_LANG['change_use_surplus'], $old_order['order_sn']));
            }

            $pay_points_change = $old_order['integral'] - $order['integral'];
            if ($pay_points_change != 0)
            {
                log_account_change($user['user_id'], 0, 0, 0, $pay_points_change, sprintf($_LANG['change_use_integral'], $old_order['order_sn']));
            }

            if ($old_order['bonus_id'] != $order['bonus_id'])
            {
                if ($old_order['bonus_id'] > 0)
                {
                    $sql = "UPDATE " . $ecs->table('user_bonus') .
                            " SET used_time = 0, order_id = 0 " .
                            "WHERE bonus_id = '$old_order[bonus_id]' LIMIT 1";
                    $db->query($sql);
                }

                if ($order['bonus_id'] > 0)
                {
                    $sql = "UPDATE " . $ecs->table('user_bonus') .
                            " SET used_time = '" . gmtime() . "', order_id = '$order_id' " .
                            "WHERE bonus_id = '$order[bonus_id]' LIMIT 1";
                    $db->query($sql);
                }
            }
        }

        if (isset($_POST['finish']))
        {
            /* 完成 */
            if ($step_act == 'add')
            {
                /* 订单改为已确认，（已付款） */
                $arr['order_status'] = OS_CONFIRMED;
                $arr['confirm_time'] = gmtime();
                if ($order['order_amount'] <= 0)
                {
                    $arr['pay_status']  = PS_PAYED;
                    $arr['pay_time']    = gmtime();
                }
                update_order($order_id, $arr);
            }

            /* 初始化提示信息和链接 */
            $msgs   = array();
            $links  = array();

            /* 如果已付款，检查金额是否变动，并执行相应操作 */
            $order = order_info($order_id);
            handle_order_money_change($order, $msgs, $links);

            /* 显示提示信息 */
            if (!empty($msgs))
            {
                sys_msg(join(chr(13), $msgs), 0, $links);
            }
            else
            {
                ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
                exit;
            }
        }
    }
    /* 保存发货后的配送方式和发货单号 */
    elseif ('invoice' == $step)
    {
        /* 如果不存在实体商品，退出 */
        if (!exist_real_goods($order_id))
        {
            die ('Hacking Attemp');
        }

        /* 保存订单 */
        $shipping_id    = $_POST['shipping'];
        $shipping       = shipping_info($shipping_id);
        $invoice_no     = trim($_POST['invoice_no']);
        $invoice_no     = str_replace(',', '<br>', $invoice_no);
        $order = array(
            'shipping_id'   => $shipping_id,
            'shipping_name' => addslashes($shipping['shipping_name']),
            'invoice_no'    => $invoice_no
        );
        update_order($order_id, $order);

        /* todo 记录日志 */
        $sn = $old_order['order_sn'];
        admin_log($sn, 'edit', 'order');

        if (isset($_POST['finish']))
        {
            ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
            exit;
        }
    }
}

/*------------------------------------------------------ */
//-- 修改订单（载入页面）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'add' || $_REQUEST['act'] == 'edit')
{
    /* 检查权限 */
    admin_priv('order_edit');

    /* 取得参数 order_id */
    $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;
    $smarty->assign('order_id', $order_id);

    /* 取得参数 step */
    $step_list = array('user', 'goods', 'consignee', 'shipping', 'payment', 'other', 'money');
    $step = isset($_GET['step']) && in_array($_GET['step'], $step_list) ? $_GET['step'] : 'user';
    $smarty->assign('step', $step);

    /* 取得参数 act */
    $act = $_GET['act'];
    $smarty->assign('ur_here',$_LANG['add_order']);
    $smarty->assign('step_act', $act);

    /* 取得订单信息 */
    if ($order_id > 0)
    {
        $order = order_info($order_id);
        $agency_id=$order['agency_id'];//办事处ID
        $pay_id=$order['pay_id'];//支付ID

        /* 发货单格式化 */
        $order['invoice_no'] = str_replace('<br>', ',', $order['invoice_no']);

        /* 如果已发货，就不能修改订单了（配送方式和发货单号除外） */
        if ($order['shipping_status'] == SS_SHIPPED || $order['shipping_status'] == SS_RECEIVED)
        {
            if ($step != 'shipping')
            {
                sys_msg($_LANG['cannot_edit_order_shipped']);
            }
            else
            {
                $step = 'invoice';
                $smarty->assign('step', $step);
            }
        }

        $smarty->assign('order', $order);
    }
    else
    {
        if ($act != 'add' || $step != 'user')
        {
            die('invalid params');
        }
    }

    /* 选择会员 */
    if ('user' == $step)
    {

        // /* 取得可用的支付方式列表 */
        $payment_list = payment_list();
        // dump($payment_list);
        $smarty->assign('payment_list', $payment_list);

        /* 取得收货地址列表 */
        if ($order['user_id'] > 0)
        {
            $smarty->assign('address_list', address_list($order['user_id']));

            $address_id = isset($_REQUEST['address_id']) ? intval($_REQUEST['address_id']) : 0;
            if ($address_id > 0)
            {
                $address = address_info($address_id);
                if ($address)
                {
                    $order['consignee']     = $address['consignee'];
                    $order['country']       = $address['country'];
                    $order['province']      = $address['province'];
                    $order['city']          = $address['city'];
                    $order['district']      = $address['district'];
                    $order['email']         = $address['email'];
                    $order['address']       = $address['address'];
                    $order['zipcode']       = $address['zipcode'];
                    $order['tel']           = $address['tel'];
                    $order['mobile']        = $address['mobile'];
                    $order['sign_building'] = $address['sign_building'];
                    $order['best_time']     = $address['best_time'];
                    $smarty->assign('order', $order);
                }
            }
        }
        /* 取得地区列表 */
        $smarty->assign('country_list', get_regions());
        //AJAX返回支付方式
        if($_REQUEST['consignee']){
             include_once(ROOT_PATH . 'includes/cls_json.php');
             $json = new JSON();
             // $district_id=$_REQUEST['consignee'];
             $obj  = $json->decode($_REQUEST['consignee']);
             $consignee['province']=$obj->province; 
             $consignee['city']=$obj->city;
             $consignee['district']=$obj->district;
             $_SESSION['province']=$consignee['province'];
             $_SESSION['city']=$consignee['city'];
             $_SESSION['district']=$consignee['district'];

             if(!is_cod($consignee)){          
                $pay_id=3;
                }
            $return='<table cellpadding="3" cellspacing="1" style="margin-top:20px; ">
                        <tr>
                            <th width="100%" colspan="2" align="left" style="font-size:20px;">选择支付方式</th>
                        </tr>';
                foreach ($payment_list as $key => $payment) {
                    if($payment['pay_id']!=$pay_id){
                        $return=$return.
                            '<tr>
                                <td><input type="radio" name="payment" value="'.$payment['pay_id'].'" /></td>
                                <td>'.$payment['pay_name'].'</td>
                                <td>'.$payment['pay_desc'].'</td>
                                <td align="right">.'.$payment['pay_fee'].'</td>
                            </tr>';
                    }

                }
                //查询地区能否进行导弹送 能则添加导弹送选择
                $sql = "SELECT * FROM ".$GLOBALS['ecs']->table('daodansong_area')."WHERE region_array = '$consignee[district]' ";
                $daodansong=$db->getAll($sql);
                if($daodansong){
                    $return=$return.
                        '<tr>
                            <th width="100%" colspan="2" align="left" style="font-size:20px;">选择导弹送</th>
                        </tr>
                        <tr>
                            <td><input type="radio" name="daodansong_id" value="0" /></td>
                            <td>取消导弹送</td>
                        </tr>';

                    foreach ($daodansong as $key => $daodansong_info) {
                    $return=$return.
                        '<tr>
                            <td><input type="radio" name="daodansong_id" value="'.$daodansong_info['area_id'].'" /></td>
                            <td>'.$daodansong_info['area_name'].'</td>
                        </tr>';
                    }
                }
                 $return=$return.'</table>'; 
            $order_area_id=is_buy($consignee);//判断改区域能否购买
            if(empty($order_area_id)){
                $return="该地区无法购买";
            }
            die($json->encode($return));
        }
        // 无操作
    }

    /* 增删改商品 */
    elseif ('goods' == $step)
    {   
        /* 取得订单商品 */
        $sql = "SELECT o.rec_id, o.goods_id, o.goods_name,o.goods_attr_sku,o.compose_note, o.goods_sku, o.market_price, o.goods_number, g.goods_weight, gs.goods_number AS goods_stock, " .
            "o.goods_price, o.goods_attr, o.is_real, o.parent_id, o.is_gift, g.give_integral, " .
            "o.goods_price * o.goods_number AS subtotal, o.extension_code " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " o ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " g ON g.goods_id = o.goods_id " .
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods_stock') . " gs ON gs.goods_id = o.goods_id AND gs.goods_attr_id = o.goods_attr_id AND gs.area_id = $agency_id" .
            " WHERE o.order_id = '$order_id'";

            // $out_trade_no=2014091346524;
            //         //修改订单状态
            // $sql = "UPDATE " .$GLOBALS['ecs']->table('order_info').
            // " SET order_status = '1' , shipping_status='0', pay_status='2',money_paid=order_amount, pay_time='" .time(). "', confirm_time='" .time(). "' WHERE order_sn='$out_trade_no' ";
            // $return=$db->query($sql);
            // //查询订单ID
            // $sql = "SELECT order_id FROM ".$GLOBALS['ecs']->table('order_info')."WHERE order_sn = $out_trade_no ";
            // $order_id = $db->getOne($sql);
            // //修改PAY_log表
            // $sql = "UPDATE " .$GLOBALS['ecs']->table('pay_log').
            // " SET is_paid = '1'  WHERE order_id ='$order_id' AND is_paid = 0 ";
            // $db->query($sql);

            // exit();

        $goods_list = $db->getAll($sql);
    
        if (!empty($goods_list))
        {  
            foreach ($goods_list AS $key => $value)
            {   
                /*读取内存库存*/
                $value['goods_stock'] = empty($value['goods_attr_sku'])?$GLOBALS['virtualStock']->selectStock($value['goods_sku']):$GLOBALS['virtualStock']->selectStock($value['goods_attr_sku']);
                $goods_list_b[$key+1]=$value;
                $count=$value['goods_number']+$count;
                $weight=$value['goods_weight']+$weight;
            }
            $goods_list=$goods_list_b;
        }
        $province_list = get_regions(1, 1);
        $city_list     = get_regions(2, $order['province']);
        $district_list = get_regions(3, $order['city']);
        $smarty->assign('province_list', $province_list);//省列表
        $smarty->assign('city_list',     $city_list);//市列表
        $smarty->assign('district_list', $district_list);//区列表
        $smarty->assign('country_list', get_regions());




        $smarty->assign('count', $count);
        $smarty->assign('goods_list', $goods_list);
        $smarty->assign('from_ad', $order['from_ad']);
        //  $smarty->assign('goods', $goods_list);
        /*获取商品运费*/


        //判断订单中是否有免邮商品
        $sql="SELECT is_shipping FROM ".$GLOBALS['ecs']->table('goods') ." AS g ".
             " LEFT JOIN ".$GLOBALS['ecs']->table('order_goods')."AS o ".
             " ON g.goods_id = o.goods_id ".
             " WHERE o.order_id=$order_id AND is_shipping=1";
        $is_shipping=$db->getOne($sql);
        /*获取商品运费*/
        $shipping_fee=shipping_fee(order_amount($order_id),$pay_id,$is_shipping,'0',$order,$weight,$order['user_id']);
        $smarty->assign('shipping_fee', $shipping_fee);
        /* 取得商品总金额 */
        $smarty->assign('goods_amount', order_amount($order_id));
        /*应支付金额*/
        $pay_fee=order_amount($order_id)+$shipping_fee; 
        $smarty->assign('pay_fee', $pay_fee);
        /*查询订单是否已支付了金额*/
        $sql="SELECT order_amount FROM ".$GLOBALS['ecs']->table('pay_log') .
             "WHERE order_id=$order_id AND is_paid = 1";
        $paid=$db->getOne($sql);
        if($paid){
             $smarty->assign('paid',$order['money_paid']);//已支付金额
             $smarty->assign('pay',$order['order_amount']);//待支付金额
        }
    }

    // 设置收货人
    elseif ('consignee' == $step)
    {
        /* 查询是否存在实体商品 */
        $exist_real_goods = exist_real_goods($order_id);
        $smarty->assign('exist_real_goods', $exist_real_goods);

        /* 取得收货地址列表 */
        if ($order['user_id'] > 0)
        {   

            $smarty->assign('address_list', address_list($order['user_id']));

            $address_id = isset($_REQUEST['address_id']) ? intval($_REQUEST['address_id']) : 0;
            if ($address_id > 0)
            {
                $address = address_info($address_id);
                if ($address)
                {
                    $order['consignee']     = $address['consignee'];
                    $order['country']       = $address['country'];
                    $order['province']      = $address['province'];
                    $order['city']          = $address['city'];
                    $order['district']      = $address['district'];
                    $order['email']         = $address['email'];
                    $order['address']       = $address['address'];
                    $order['zipcode']       = $address['zipcode'];
                    $order['tel']           = $address['tel'];
                    $order['mobile']        = $address['mobile'];
                    $order['sign_building'] = $address['sign_building'];
                    $order['best_time']     = $address['best_time'];
                    $smarty->assign('order', $order);
                }
            }
        }
        
        if ($exist_real_goods)
        {
            /* 取得国家 */
            $smarty->assign('country_list', get_regions());
            if ($order['country'] > 0)
            {
                /* 取得省份 */
                $smarty->assign('province_list', get_regions(1, $order['country']));
                if ($order['province'] > 0)
                {
                    /* 取得城市 */
                    $smarty->assign('city_list', get_regions(2, $order['province']));
                    if ($order['city'] > 0)
                    {
                        /* 取得区域 */
                        $smarty->assign('district_list', get_regions(3, $order['city']));
                    }
                }
            }
        }
    }

    // 选择配送方式
    elseif ('shipping' == $step)
    {
        /* 如果不存在实体商品 */
        if (!exist_real_goods($order_id))
        {
            die ('Hacking Attemp');
        }

        /* 取得可用的配送方式列表 */
        $region_id_list = array(
            $order['country'], $order['province'], $order['city'], $order['district']
        );
        $shipping_list = available_shipping_list($region_id_list);

        /* 取得配送费用 */
        $total = order_weight_price($order_id);
        foreach ($shipping_list AS $key => $shipping)
        {
            $shipping_fee = shipping_fee($shipping['shipping_code'],
                unserialize($shipping['configure']), $total['weight'], $total['amount'], $total['number'],$order['user_id']);
            $shipping_list[$key]['shipping_fee'] = $shipping_fee;
            $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee);
            $shipping_list[$key]['free_money'] = price_format($shipping['configure']['free_money']);
        }
        $smarty->assign('shipping_list', $shipping_list);
    }

    // 选择支付方式
    elseif ('payment' == $step)
    {
        /* 取得可用的支付方式列表 */
        if (exist_real_goods($order_id))
        {
            /* 存在实体商品 */
            $region_id_list = array(
                $order['country'], $order['province'], $order['city'], $order['district']
            );
            $shipping_area = shipping_area_info($order['shipping_id'], $region_id_list);
            $pay_fee = ($shipping_area['support_cod'] == 1) ? $shipping_area['pay_fee'] : 0;

            $payment_list = available_payment_list($shipping_area['support_cod'], $pay_fee);
        }
        else
        {
            /* 不存在实体商品 */
            $payment_list = available_payment_list(false);
        }

        /* 过滤掉使用余额支付 */
        foreach ($payment_list as $key => $payment)
        {
            if ($payment['pay_code'] == 'balance')
            {
                unset($payment_list[$key]);
            }
        }
        $smarty->assign('payment_list', $payment_list);
    }



    // 费用
    elseif ('money' == $step)
    {
        /* 查询是否存在实体商品 */
        $exist_real_goods = exist_real_goods($order_id);
        $smarty->assign('exist_real_goods', $exist_real_goods);

        /* 取得用户信息 */
        if ($order['user_id'] > 0)
        {
            $user = user_info($order['user_id']);

            /* 计算可用余额 */
            $smarty->assign('available_user_money', $order['surplus'] + $user['user_money']);

            /* 计算可用积分 */
            $smarty->assign('available_pay_points', $order['integral'] + $user['pay_points']);

            /* 取得用户可用红包 */
            $user_bonus = user_bonus($order['user_id'], $order['goods_amount']);
            if ($order['bonus_id'] > 0)
            {
                $bonus = bonus_info($order['bonus_id']);
                $user_bonus[] = $bonus;
            }
            $smarty->assign('available_bonus', $user_bonus);
        }
    }

    // 发货后修改配送方式和发货单号
    elseif ('invoice' == $step)
    {
        /* 如果不存在实体商品 */
        if (!exist_real_goods($order_id))
        {
            die ('Hacking Attemp');
        }

        /* 取得可用的配送方式列表 */
        $region_id_list = array(
            $order['country'], $order['province'], $order['city'], $order['district']
        );
        $shipping_list = available_shipping_list($region_id_list);

//        /* 取得配送费用 */
//        $total = order_weight_price($order_id);
//        foreach ($shipping_list AS $key => $shipping)
//        {
//            $shipping_fee = shipping_fee($shipping['shipping_code'],
//                unserialize($shipping['configure']), $total['weight'], $total['amount'], $total['number']);
//            $shipping_list[$key]['shipping_fee'] = $shipping_fee;
//            $shipping_list[$key]['format_shipping_fee'] = price_format($shipping_fee);
//            $shipping_list[$key]['free_money'] = price_format($shipping['configure']['free_money']);
//        }
        $smarty->assign('shipping_list', $shipping_list);
    }

    /* 显示模板 */
    assign_query_info();
    $smarty->display('order_step.htm');
}

/*------------------------------------------------------ */
//-- 处理
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'process')
{
    /* 取得参数 func */
    $func = isset($_GET['func']) ? $_GET['func'] : '';

    /* 删除订单商品 */
    if ('drop_order_goods' == $func)
    {
        /* 检查权限 */
        admin_priv('order_edit');

        /* 取得参数 */
        $rec_id = intval($_GET['rec_id']);
        $step_act = $_GET['step_act'];
        $order_id = intval($_GET['order_id']);
        /*如果是编辑状态则修改库存*/
        if($_REQUEST['step_act']=='edit'){
            //获取订单商品
            $order=order_info($order_id);
            $area_id = $order['agency_id'];
            $sql="SELECT rec_id,goods_sku,goods_attr_sku,compose_note,goods_number ,goods_name,goods_attr".
                " FROM ".$GLOBALS['ecs']->table('order_goods').
                " WHERE order_id = $order_id AND rec_id =$rec_id ";
            $order_goods=$db->getRow($sql);

            if($order_goods){
                /*增加库存*/
                $sku = empty($order_goods['goods_attr_sku'])?$order_goods['goods_sku']:$order_goods['goods_attr_sku'];
                change_goods_storage($sku,3,$order_goods['goods_number']);
            }
        }
        /* 删除 */
        $sql = "DELETE FROM " . $ecs->table('order_goods') .
                " WHERE rec_id = '$rec_id' LIMIT 1";
        $db->query($sql);

        /* 更新商品总金额和订单总金额 */
        update_order($order_id, array('goods_amount' => order_amount($order_id)));
        update_order_amount($order_id);
        /* 跳回订单商品 */
        ecs_header("Location: order.php?act=" . $step_act . "&order_id=" . $order_id . "&step=goods\n");
        exit;
    }

    /* 取消刚添加或编辑的订单 */
    elseif ('cancel_order' == $func)
    {
        $step_act = $_GET['step_act'];
        $order_id = isset($_GET['order_id']) ? intval($_GET['order_id']) : 0;

    }

    /* 编辑订单时由于订单已付款且金额减少而退款 */
    elseif ('refund' == $func)
    {
        /* 处理退款 */
        $order_id       = $_REQUEST['order_id'];
        $refund_type    = $_REQUEST['refund'];
        $refund_note    = $_REQUEST['refund_note'];
        $refund_amount  = $_REQUEST['refund_amount'];
        $order          = order_info($order_id);
        order_refund($order, $refund_type, $refund_note, $refund_amount);

        /* 修改应付款金额为0，已付款金额减少 $refund_amount */
        update_order($order_id, array('order_amount' => 0, 'money_paid' => $order['money_paid'] - $refund_amount));

        /* 返回订单详情 */
        ecs_header("Location: order.php?act=info&order_id=" . $order_id . "\n");
        exit;
    }

    /* 载入退款页面 */
    elseif ('load_refund' == $func)
    {
        $refund_amount = floatval($_REQUEST['refund_amount']);
        $smarty->assign('refund_amount', $refund_amount);
        $smarty->assign('formated_refund_amount', price_format($refund_amount));

        $anonymous = $_REQUEST['anonymous'];
        $smarty->assign('anonymous', $anonymous); // 是否匿名

        $order_id = intval($_REQUEST['order_id']);
        $smarty->assign('order_id', $order_id); // 订单id

        /* 显示模板 */
        $smarty->assign('ur_here', $_LANG['refund']);
        assign_query_info();
        $smarty->display('order_refund.htm');
    }

    else
    {
        die('invalid params');
    }
}

/*------------------------------------------------------ */
//-- 合并订单
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'merge')
{
    /* 检查权限 */
    admin_priv('order_os_edit');

    /* 取得满足条件的订单 */
    $sql = "SELECT o.order_sn, u.user_name " .
            "FROM " . $ecs->table('order_info') . " AS o " .
                "LEFT JOIN " . $ecs->table('users') . " AS u ON o.user_id = u.user_id " .
            "WHERE o.user_id > 0 " .
            "AND o.extension_code = '' " . order_query_sql('unprocessed') . ' ORDER BY o.order_id DESC';
    $smarty->assign('order_list', $db->getAll($sql));

    /* 模板赋值 */
    $smarty->assign('ur_here', $_LANG['04_merge_order']);
    $smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => $_LANG['02_order_list']));

    /* 显示模板 */
    assign_query_info();
    $smarty->display('merge_order.htm');
}

/*------------------------------------------------------ */
//-- 操作订单状态（载入页面）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'operate')
{
    $order_id = '';
    /* 检查权限 */
    admin_priv('order_os_edit');

    /* 取得订单id（可能是多个，多个sn）和操作备注（可能没有） */
    if(isset($_REQUEST['order_id']))
    {
        $order_id= $_REQUEST['order_id'];
    }
    $batch          = isset($_REQUEST['batch']); // 是否批处理
    $action_note    = isset($_REQUEST['action_note']) ? trim($_REQUEST['action_note']) : '';

    /* 确认 */
    if (isset($_POST['confirm']))
    {
        $require_note   = false;
        $action         = $_LANG['op_confirm'];
        $operation      = 'confirm';
    }
    /* 付款 */
    elseif (isset($_POST['pay']))
    {   
        /* 检查权限 */
        admin_priv('order_ps_edit');
        $require_note   = $_CFG['order_pay_note'] == 1;
        $action         = $_LANG['op_pay'];
        $operation      = 'pay';

    }
    /* 未付款 */
    elseif (isset($_POST['unpay']))
    {
        /* 检查权限 */
        admin_priv('order_ps_edit');

        $require_note   = $_CFG['order_unpay_note'] == 1;
        $order          = order_info($order_id);
        if ($order['money_paid'] > 0)
        {
            $show_refund = true;
        }
        $anonymous      = $order['user_id'] == 0;
        $action         = $_LANG['op_unpay'];
        $operation      = 'unpay';
    }
    /* 未发货 */
    elseif (isset($_POST['unship']))
    {
        /* 检查权限 */
        admin_priv('order_ss_edit');

        $require_note   = $_CFG['order_unship_note'] == 1;
        $action         = $_LANG['op_unship'];
        $operation      = 'unship';
    }
    /* 收货确认 */
    elseif (isset($_POST['receive']))
    {
        $require_note   = $_CFG['order_receive_note'] == 1;
        $action         = $_LANG['op_receive'];
        $operation      = 'receive';
    }
    /* 取消 */
    elseif (isset($_POST['cancel']))
    {   
        $require_note   = $_CFG['order_cancel_note'] == 1;
        $action         = $_LANG['op_cancel'];
        $operation      = 'cancel';
        $show_cancel_note   = true;
        $order          = order_info($order_id);
        if ($order['money_paid'] > 0)
        {
            $show_refund = true;
        }
        $anonymous      = $order['user_id'] == 0;
    }
    /* 售后 */
    elseif (isset($_POST['after_service']))
    {
        $require_note   = true;
        $action         = $_LANG['op_after_service'];
        $operation      = 'after_service';
        $after_service_cause = $_POST['after_service_cause'];
        $after_service_result = $_POST['after_service_result'];
        $refund = $_POST['refund'];
        ecs_header("Location: order.php?act=operate_post&order_id=" . $order_id . "&after_service_cause=$after_service_cause&after_service_result=$after_service_result&refund=$refund" . 
                "&operation=" . $operation . "&action_note=" . urlencode($action_note) . "\n");
        exit;
    }
    /* 指派 */
    elseif (isset($_POST['assign']))
    {
        /* 取得参数 */
        $new_agency_id  = isset($_POST['agency_id']) ? intval($_POST['agency_id']) : 0;
        if ($new_agency_id == 0)
        {
            sys_msg($_LANG['js_languages']['pls_select_agency']);
        }

        /* 查询订单信息 */
        $order = order_info($order_id);

        /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
        $sql = "SELECT agency_id FROM " . $ecs->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $admin_agency_id = $db->getOne($sql);
        if ($admin_agency_id > 0)
        {
            if ($order['agency_id'] != $admin_agency_id)
            {
                sys_msg($_LANG['priv_error']);
            }
        }

        /* 修改订单相关所属的办事处 */
        if ($new_agency_id != $order['agency_id'])
        {   
            /*修改指派地区库存增加库存*/
            change_order_goods_storage($order_id,false);
            $db->query("UPDATE " . $ecs->table('order_info') . " SET agency_id = '$new_agency_id' " .
                "WHERE order_id = '$order_id'");
            /*修改指派地区库存减少库存*/
            change_order_goods_storage($order_id);
        }

        /* 操作成功 */
        $links[] = array('href' => 'order.php?act=list&' . list_link_postfix(), 'text' => $_LANG['02_order_list']);
        sys_msg($_LANG['act_ok'], 0, $links);
    }
    /* 退款 */
    elseif (isset($_POST['refund']))
    {
        $order = order_info($order_id);
        if((!$_POST['refund_amount'] && $_POST['refund_amount'] != '0') || $_POST['refund_amount']>$order['total_fee']){
            $links[] = array('href' => 'order.php?act=info&order_id=' . $order_id, 'text' => $_LANG['order_info']);
            sys_msg('请填写退款金额，不得大于订单总金额', 0, $links);
            exit;
        }
        $data['money'] = -$_POST['refund_amount'];
        $data['user_id'] = $order['user_id'];
        $data['extension_code'] = 'refund_' . $order['order_sn'];
        $data['note'] = '退款订单号：' . $order['order_sn'];
        auto_receive_freeplan($data);// 奖金更新
        update_order($order_id, array('refund_amount'=>floatval($_POST['refund_amount']),'to_buyer' => "[售后]退款金额：$_POST[refund_amount]"));// 更新订单信息
        order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], "[售后][退款]最终退款金额：$data[money]；备注：" . $action_note, null, 0, intval($_REQUEST['after_service_cause']), intval($_REQUEST['after_service_result'])); // 记录操作信息
        /* 操作成功 */
        $links[] = array('href' => 'order.php?act=info&order_id=' . $order_id, 'text' => $_LANG['order_info']);
        sys_msg('退款成功', 0, $links);
    }
    /* 订单删除 */
    elseif (isset($_POST['remove']))
    {
        $require_note = false;
        $operation = 'remove';
        if (!$batch)
        {
            /* 检查能否操作 */
            $order = order_info($order_id);
            $operable_list = operable_list($order);
            if (!isset($operable_list['remove']))
            {
                die('Hacking attempt');
            }

            /* 删除订单 */
            $db->query("DELETE FROM ".$ecs->table('order_info'). " WHERE order_id = '$order_id'");
            $db->query("DELETE FROM ".$ecs->table('order_goods'). " WHERE order_id = '$order_id'");
            $db->query("DELETE FROM ".$ecs->table('order_action'). " WHERE order_id = '$order_id'");
            $action_array = array('delivery', 'back');
            del_delivery($order_id, $action_array);

            /* todo 记录日志 */
            admin_log($order['order_sn'], 'remove', 'order');

            /* 返回 */
            sys_msg($_LANG['order_removed'], 0, array(array('href'=>'order.php?act=list&' . list_link_postfix(), 'text' => $_LANG['return_list'])));
        }
    }
    /* 批量打印订单 */
    elseif (isset($_POST['print']))
    {
        if (empty($_POST['order_id']))
        {
            sys_msg($_LANG['pls_select_order']);
        }

        /* 赋值公用信息 */
        $smarty->assign('shop_name',    $_CFG['shop_name']);
        $smarty->assign('shop_url',     $ecs->url());
        $smarty->assign('shop_address', $_CFG['shop_address']);
        $smarty->assign('service_phone',$_CFG['service_phone']);
        $smarty->assign('print_time',   local_date($_CFG['time_format']));
        $smarty->assign('action_user',  $_SESSION['admin_name']);

        $html = '';
        $order_sn_list = explode(',', $_POST['order_id']);
        foreach ($order_sn_list as $order_sn)
        {
            /* 取得订单信息 */
            $order = order_info(0, $order_sn);
            if (empty($order))
            {
                continue;
            }

            /* 根据订单是否完成检查权限 */
            if (order_finished($order))
            {
                if (!admin_priv('order_view_finished', '', false))
                {
                    continue;
                }
            }
            else
            {
                if (!admin_priv('order_view', '', false))
                {
                    continue;
                }
            }

            /* 如果管理员属于某个办事处，检查该订单是否也属于这个办事处 */
            $sql = "SELECT agency_id FROM " . $ecs->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
            $agency_id = $db->getOne($sql);
            if ($agency_id > 0)
            {
                if ($order['agency_id'] != $agency_id)
                {
                    continue;
                }
            }

            /* 取得用户名 */
            if ($order['user_id'] > 0)
            {
                $user = user_info($order['user_id']);
                if (!empty($user))
                {
                    $order['user_name'] = $user['user_name'];
                }
            }

            /* 取得区域名 */
            $sql = "SELECT concat(IFNULL(c.region_name, ''), '  ', IFNULL(p.region_name, ''), " .
                        "'  ', IFNULL(t.region_name, ''), '  ', IFNULL(d.region_name, '')) AS region " .
                    "FROM " . $ecs->table('order_info') . " AS o " .
                        "LEFT JOIN " . $ecs->table('region') . " AS c ON o.country = c.region_id " .
                        "LEFT JOIN " . $ecs->table('region') . " AS p ON o.province = p.region_id " .
                        "LEFT JOIN " . $ecs->table('region') . " AS t ON o.city = t.region_id " .
                        "LEFT JOIN " . $ecs->table('region') . " AS d ON o.district = d.region_id " .
                    "WHERE o.order_id = '$order[order_id]'";
            $order['region'] = $db->getOne($sql);

            /* 其他处理 */
            $order['order_time']    = local_date($_CFG['time_format'], $order['add_time']);
            $order['pay_time']      = $order['pay_time'] > 0 ?
                local_date($_CFG['time_format'], $order['pay_time']) : $_LANG['ps'][PS_UNPAYED];
            $order['shipping_time'] = $order['shipping_time'] > 0 ?
                local_date($_CFG['time_format'], $order['shipping_time']) : $_LANG['ss'][SS_UNSHIPPED];
            $order['status']        = $_LANG['os'][$order['order_status']] . ',' . $_LANG['ps'][$order['pay_status']] . ',' . $_LANG['ss'][$order['shipping_status']];
            $order['invoice_no']    = $order['shipping_status'] == SS_UNSHIPPED || $order['shipping_status'] == SS_PREPARING ? $_LANG['ss'][SS_UNSHIPPED] : $order['invoice_no'];

            /* 此订单的发货备注(此订单的最后一条操作记录) */
            $sql = "SELECT action_note FROM " . $ecs->table('order_action').
                   " WHERE order_id = '$order[order_id]' AND shipping_status = 1 ORDER BY log_time DESC";
            $order['invoice_note'] = $db->getOne($sql);

            /* 参数赋值：订单 */
            $smarty->assign('order', $order);

            /* 取得订单商品 */
            $goods_list = array();
            $goods_attr = array();
            $sql = "SELECT o.*, g.goods_number AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
                    "FROM " . $ecs->table('order_goods') . " AS o ".
                    "LEFT JOIN " . $ecs->table('goods') . " AS g ON o.goods_id = g.goods_id " .
                    "LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " .
                    "WHERE o.order_id = '$order[order_id]' ";
            $res = $db->query($sql);
            while ($row = $db->fetchRow($res))
            {
                /* 虚拟商品支持 */
                if ($row['is_real'] == 0)
                {
                    /* 取得语言项 */
                    $filename = ROOT_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $_CFG['lang'] . '.php';
                    if (file_exists($filename))
                    {
                        include_once($filename);
                        if (!empty($_LANG[$row['extension_code'].'_link']))
                        {
                            $row['goods_name'] = $row['goods_name'] . sprintf($_LANG[$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
                        }
                    }
                }

                $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
                $row['formated_goods_price']    = price_format($row['goods_price']);

                $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组
                $goods_list[] = $row;
            }

            $attr = array();
            $arr  = array();
            foreach ($goods_attr AS $index => $array_val)
            {
                foreach ($array_val AS $value)
                {
                    $arr = explode(':', $value);//以 : 号将属性拆开
                    $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
                }
            }

            $smarty->assign('goods_attr', $attr);
            $smarty->assign('goods_list', $goods_list);

            $smarty->template_dir = '../' . DATA_DIR;
            $html .= $smarty->fetch('order_print.html') .
                '<div style="PAGE-BREAK-AFTER:always"></div>';
        }

        echo $html;
        exit;
    }
    /* 直接处理还是跳到详细页面 */
    if (($require_note && $action_note == '') || isset($show_invoice_no) || isset($show_refund))
    {

        /* 模板赋值 */
        $smarty->assign('require_note', $require_note); // 是否要求填写备注
        $smarty->assign('action_note', $action_note);   // 备注
        $smarty->assign('show_cancel_note', isset($show_cancel_note)); // 是否显示取消原因
        $smarty->assign('show_invoice_no', isset($show_invoice_no)); // 是否显示发货单号
        $smarty->assign('show_refund', isset($show_refund)); // 是否显示退款
        $smarty->assign('anonymous', isset($anonymous) ? $anonymous : true); // 是否匿名
        $smarty->assign('order_id', $order_id); // 订单id
        $smarty->assign('batch', $batch);   // 是否批处理
        $smarty->assign('operation', $operation); // 操作

        /* 显示模板 */
        $smarty->assign('ur_here', $_LANG['order_operate'] . $action);
        assign_query_info();
        $smarty->display('order_operate.htm');
    }
    else
    {
        /* 直接处理 */
        if (!$batch)
        {
            /* 一个订单 */
            ecs_header("Location: order.php?act=operate_post&order_id=" . $order_id .
                    "&operation=" . $operation . "&action_note=" . urlencode($action_note) . "\n");
            exit;
        }
        else
        {
            /* 多个订单 */
            ecs_header("Location: order.php?act=batch_operate_post&order_id=" . $order_id .
                    "&operation=" . $operation . "&action_note=" . urlencode($action_note) . "\n");
            exit;
        }
    }
}

/*------------------------------------------------------ */
//-- 操作订单状态（处理批量提交）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'batch_operate_post')
{
    /* 检查权限 */
    admin_priv('order_os_edit');

    /* 取得参数 */
    $order_id   = $_REQUEST['order_id'];        // 订单id（逗号格开的多个订单id）
    $operation  = $_REQUEST['operation'];       // 订单操作
    $action_note= $_REQUEST['action_note'];     // 操作备注

    $order_id_list = explode(',', $order_id);

    /* 初始化处理的订单sn */
    $sn_list = array();
    $sn_not_list = array();

    /* 确认 */
    if ('confirm' == $operation)
    {
        foreach($order_id_list as $id_order)
        {
            $sql = "SELECT * FROM " . $ecs->table('order_info') .
                " WHERE order_sn = '$id_order'" .
                " AND order_status = '" . OS_UNCONFIRMED . "'";
            $order = $db->getRow($sql);

            if($order)
            {
                 /* 检查能否操作 */
                $operable_list = operable_list($order);
                if (!isset($operable_list[$operation]))
                {
                    $sn_not_list[] = $id_order;
                    continue;
                }

                $order_id = $order['order_id'];

                /* 标记订单为已确认 */
                update_order($order_id, array('order_status' => OS_CONFIRMED, 'confirm_time' => gmtime()));
                update_order_amount($order_id);

                /* 记录log */
                order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);

                /* 发送邮件 */
                if ($_CFG['send_confirm_email'] == '1')
                {
                    $tpl = get_mail_template('order_confirm');
                    $order['formated_add_time'] = local_date($GLOBALS['_CFG']['time_format'], $order['add_time']);
                    $smarty->assign('order', $order);
                    $smarty->assign('shop_name', $_CFG['shop_name']);
                    $smarty->assign('send_date', local_date($_CFG['date_format']));
                    $smarty->assign('sent_date', local_date($_CFG['date_format']));
                    $content = $smarty->fetch('str:' . $tpl['template_content']);
                    send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);
                }

                $sn_list[] = $order['order_sn'];
            }
            else
            {
                $sn_not_list[] = $id_order;
            }
        }

        $sn_str = $_LANG['confirm_order'];
    }
    /* 取消 */
    elseif ('cancel' == $operation)
    {
        foreach($order_id_list as $id_order)
        {
            $sql = "SELECT * FROM " . $ecs->table('order_info') .
                " WHERE order_sn = $id_order" . order_query_sql('unpay_unship');

            $order = $db->getRow($sql);
            if($order)
            {
                 /* 检查能否操作 */
                $operable_list = operable_list($order);
                if (!isset($operable_list[$operation]))
                {
                    $sn_not_list[] = $id_order;
                    continue;
                }

                $order_id = $order['order_id'];

                /* 标记订单为“取消”，记录取消原因 */
                $cancel_note = trim($_REQUEST['cancel_note']);
                update_order($order_id, array('order_status' => OS_CANCELED, 'to_buyer' => $cancel_note,'pay_status' => PS_UNPAYED,'pay_time' => 0,'money_paid'    => 0,'wangcangstatus'=> 0,'order_amount' => $order['money_paid']));
                /* 记录log */
                order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED, $action_note);

                /* 如果使用库存，且下订单时减库存，则增加库存 */
                if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE)
                {
                    //取消订单增加库存
                    change_order_goods_storage($order_id,false);
                    order_receive_freeplan($order,2);//减少奖金
                }
                /* 发送邮件 */
                if ($_CFG['send_cancel_email'] == '1')
                {
                    $tpl = get_mail_template('order_cancel');
                    $smarty->assign('order', $order);
                    $smarty->assign('shop_name', $_CFG['shop_name']);
                    $smarty->assign('send_date', local_date($_CFG['date_format']));
                    $smarty->assign('sent_date', local_date($_CFG['date_format']));
                    $content = $smarty->fetch('str:' . $tpl['template_content']);
                    send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);
                }

                $sn_list[] = $order['order_sn'];
             }
            else
            {
                $sn_not_list[] = $id_order;
            }
        }
        if(!empty($sn_list)){
            require_once(ROOT_PATH . 'includes/lib_wangcang.php');
            vgetcancelTrade($sn_list, $v_data);
        }

        $sn_str = $_LANG['cancel_order'];
    }
    /* 移除 */
    elseif ('remove' == $operation)
    {
        foreach ($order_id_list as $id_order)
        {
            /* 检查能否操作 */
            $order = order_info('', $id_order);
            $operable_list = operable_list($order);
            if (!isset($operable_list['remove']))
            {
                $sn_not_list[] = $id_order;
                continue;
            }

            /* 删除订单 */
            $db->query("DELETE FROM ".$ecs->table('order_info'). " WHERE order_id = '$order[order_id]'");
            $db->query("DELETE FROM ".$ecs->table('order_goods'). " WHERE order_id = '$order[order_id]'");
            $db->query("DELETE FROM ".$ecs->table('order_action'). " WHERE order_id = '$order[order_id]'");
            $action_array = array('delivery', 'back');
            del_delivery($order['order_id'], $action_array);

            /* todo 记录日志 */
            admin_log($order['order_sn'], 'remove', 'order');

            $sn_list[] = $order['order_sn'];
        }

        $sn_str = $_LANG['remove_order'];
    }
    else
    {
        die('invalid params');
    }

    /* 取得备注信息 */
//    $action_note = $_REQUEST['action_note'];

    if(empty($sn_not_list))
    {
        $sn_list = empty($sn_list) ? '' : $_LANG['updated_order'] . join($sn_list, ',');
        $msg = $sn_list;
        $links[] = array('text' => $_LANG['return_list'], 'href' => 'order.php?act=list&' . list_link_postfix());
        sys_msg($msg, 0, $links);
    }
    else
    {
        $order_list_no_fail = array();
        $sql = "SELECT * FROM " . $ecs->table('order_info') .
                " WHERE order_sn " . db_create_in($sn_not_list);
        $res = $db->query($sql);
        while($row = $db->fetchRow($res))
        {
            $order_list_no_fail[$row['order_id']]['order_id'] = $row['order_id'];
            $order_list_no_fail[$row['order_id']]['order_sn'] = $row['order_sn'];
            $order_list_no_fail[$row['order_id']]['order_status'] = $row['order_status'];
            $order_list_no_fail[$row['order_id']]['shipping_status'] = $row['shipping_status'];
            $order_list_no_fail[$row['order_id']]['pay_status'] = $row['pay_status'];

            $order_list_fail = '';
            foreach(operable_list($row) as $key => $value)
            {
                if($key != $operation)
                {
                    $order_list_fail .= $_LANG['op_' . $key] . ',';
                }
            }
            $order_list_no_fail[$row['order_id']]['operable'] = $order_list_fail;
        }

        /* 模板赋值 */
        $smarty->assign('order_info', $sn_str);
        $smarty->assign('action_link', array('href' => 'order.php?act=list', 'text' => $_LANG['02_order_list']));
        $smarty->assign('order_list',   $order_list_no_fail);

        /* 显示模板 */
        assign_query_info();
        $smarty->display('order_operate_info.htm');
    }
}

/*------------------------------------------------------ */
//-- 操作订单状态（处理提交）
/*------------------------------------------------------ */

elseif ($_REQUEST['act'] == 'operate_post')
{
    /* 检查权限 */
    admin_priv('order_os_edit');

    /* 取得参数 */
    $order_id   = intval(trim($_REQUEST['order_id']));        // 订单id
    $operation  = $_REQUEST['operation'];       // 订单操作

    /* 查询订单信息 */
    $order = order_info($order_id);

    /* 检查能否操作 */
    $operable_list = operable_list($order);
    if (!isset($operable_list[$operation]))
    {
        die('Hacking attempt');
    }

    /* 取得备注信息 */
    $action_note = $_REQUEST['action_note'];

    /* 初始化提示信息 */
    $msg = '';

    /* 确认 */
    if ('confirm' == $operation)
    {
        /* 如果原来状态为'取消'，则不允许进行确认操作 */
        if ($order['order_status'] == 2 && $_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE)
        {
            $msg = '取消的订单不允许直接再确认，请点击编辑商品信息进行订单重新处理！';
            // change_order_goods_storage($order_id, true, 1);
        }else{
            /* 标记订单为已确认 */
            update_order($order_id, array('order_status' => OS_CONFIRMED,'confirm_time' => gmtime()));
            update_order_amount($order_id);

            /* 记录log */
            order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);

            /* 发送邮件 */
            $cfg = $_CFG['send_confirm_email'];
            if ($cfg == '1')
            {
                $tpl = get_mail_template('order_confirm');
                $smarty->assign('order', $order);
                $smarty->assign('shop_name', $_CFG['shop_name']);
                $smarty->assign('send_date', local_date($_CFG['date_format']));
                $smarty->assign('sent_date', local_date($_CFG['date_format']));
                $content = $smarty->fetch('str:' . $tpl['template_content']);
                if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']))
                {
                    $msg = $_LANG['send_mail_fail'];
                }
            }
        }
    }
    /* 付款 */
    elseif ('pay' == $operation)
    {
        /* 检查权限 */
        admin_priv('order_ps_edit');

        /* 标记订单为已确认、已付款，更新付款时间和已支付金额，如果是货到付款，同时修改订单为“收货确认” */
        if ($order['order_status'] != OS_CONFIRMED AND $order['order_status'] != 5)
        {
            $arr['order_status']    = OS_CONFIRMED;
            $arr['confirm_time']    = gmtime();
        }
        $arr['pay_status']  = PS_PAYED;
        $arr['pay_time']    = gmtime();
        $arr['money_paid']  = $order['money_paid'] + $order['order_amount'];
        $arr['order_amount']= 0;
        $payment = payment_info($order['pay_id']);
        // if ($payment['is_cod'])
        // {
        //     $arr['shipping_status'] = SS_RECEIVED;
        //     $order['shipping_status'] = SS_RECEIVED;
        // }
        // 支付宝支付更新PAY_LOG表
        if($order['pay_id']==1){
            $sql = "UPDATE ".$GLOBALS['ecs']->table('pay_log').
             " set is_paid=1".
             " WHERE order_id=$order[order_id] AND is_paid=0";
             $db->query($sql);
        }
        update_order($order_id, $arr);
        require_once(ROOT_PATH . 'includes/lib_wangcang.php');
        $data = vsetpushTrades(array($order_id), $v_data);
        if(!empty($data['data']['successs_count'])){
            $arr['wangcangstatus']= 130;
        }
        update_order($order_id, $arr);

        /* 记录log */
        order_action($order['order_sn'], OS_CONFIRMED, $order['shipping_status'], PS_PAYED, $action_note);
    }
    /* 设为未付款 */
    elseif ('unpay' == $operation)
    {
        /* 检查权限 */
        admin_priv('order_ps_edit');

        /* 标记订单为未付款，更新付款时间和已付款金额 */
        $arr = array(
            'pay_status'    => PS_UNPAYED,
            'pay_time'      => 0,
            'money_paid'    => 0,
            'order_amount'  => $order['money_paid']
        );
        if($order['pay_id']==1){
            $sql = "UPDATE ".$GLOBALS['ecs']->table('pay_log').
             " set is_paid=0".
             " WHERE order_id=$order[order_id] AND is_paid=1";
             $db->query($sql);
        }
        update_order($order_id, $arr);

        /* 记录log */
        order_action($order['order_sn'], OS_CONFIRMED, SS_UNSHIPPED, PS_UNPAYED, $action_note);
    }
    /* 设为未发货 */
    elseif ('unship' == $operation)
    {
        /* 检查权限 */
        admin_priv('order_ss_edit');

        /* 标记订单为“未发货”，更新发货时间, 订单状态为“确认” */
        update_order($order_id, array('shipping_status' => SS_UNSHIPPED, 'shipping_time' => 0, 'invoice_no' => '', 'order_status' => OS_CONFIRMED));

        /* 记录log */
        order_action($order['order_sn'], $order['order_status'], SS_UNSHIPPED, $order['pay_status'], $action_note);

        /* 清除缓存 */
        clear_cache_files();
    }
    /* 收货确认 */
    elseif ('receive' == $operation)
    {
        /* 标记订单为“收货确认”，如果是货到付款，同时修改订单为已付款 */

        $integral = integral_to_give($order);
        log_account_change($order['user_id'], 0, 0, intval($integral['rank_points']), intval($integral['custom_points']), sprintf($_LANG['order_gift_integral'], $order['order_sn']));
        $arr = array('shipping_status' => SS_RECEIVED);
        $payment = payment_info($order['pay_id']);
        if ($payment['is_cod'])
        {
            $arr['pay_status'] = PS_PAYED;
            $order['pay_status'] = PS_PAYED;
        }
        update_order($order_id, $arr);

        /* 记录log */
        order_action($order['order_sn'], $order['order_status'], SS_RECEIVED, $order['pay_status'], $action_note);
    }
    /* 取消 */
    elseif ('cancel' == $operation)
    {

        /* 标记订单为“取消”，记录取消原因 */
        $cancel_note = isset($_REQUEST['cancel_note']) ? trim($_REQUEST['cancel_note']) : '';
        $arr = array(
            'order_status'  => OS_CANCELED,
            'to_buyer'      => $cancel_note,
            'pay_status'    => PS_UNPAYED,
            'pay_time'      => 0,
            'money_paid'    => 0,
            'wangcangstatus'=> 0,
            'order_amount'  => $order['money_paid']
        );
        update_order($order_id, $arr);

        /* 记录log */
        order_action($order['order_sn'], OS_CANCELED, $order['shipping_status'], PS_UNPAYED, $action_note);

        /* 如果使用库存，且下订单时减库存，则增加库存 */
        if ($_CFG['use_storage'] == '1' && $_CFG['stock_dec_time'] == SDT_PLACE)
        {
            //取消订单增加库存
            change_order_goods_storage($order_id,false);
            order_receive_freeplan($order,2);//减少奖金
        }
        /* 发送邮件 */
        $cfg = $_CFG['send_cancel_email'];
        if ($cfg == '1')
        {
            $tpl = get_mail_template('order_cancel');
            $smarty->assign('order', $order);
            $smarty->assign('shop_name', $_CFG['shop_name']);
            $smarty->assign('send_date', local_date($_CFG['date_format']));
            $smarty->assign('sent_date', local_date($_CFG['date_format']));
            $content = $smarty->fetch('str:' . $tpl['template_content']);
            if (!send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']))
            {
                $msg = $_LANG['send_mail_fail'];
            }
        }
        require_once(ROOT_PATH . 'includes/lib_wangcang.php');
        vgetcancelTrade(array($order['order_sn']), $v_data);
    }
    /* 售后服务 */
    elseif ('after_service' == $operation)
    {
        /* 记录log */
        order_action($order['order_sn'], $order['order_status'], $order['shipping_status'], $order['pay_status'], '[售后] ' . $action_note, null, 0, intval($_REQUEST['after_service_cause']), intval($_REQUEST['after_service_result']));
        if($_REQUEST['refund']){

        }
    }
    else
    {
        die('invalid params');
    }

    /* 操作成功 */
    $links[] = array('text' => $_LANG['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
    sys_msg($_LANG['act_ok'] . $msg, 0, $links);
}

elseif ($_REQUEST['act'] == 'json')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();

    $func = $_REQUEST['func'];
    if ($func == 'get_goods_info')
    {
         /* 通过商品ID获取商品信息 */
        $goods_id = $_REQUEST['goods_id'];//商品ID
        $order_id = $_REQUEST['order_id'];
        // 获取订单服务区域
        $sql = 'SELECT agency_id,from_ad FROM'.$GLOBALS['ecs']->table('order_info') ." WHERE order_id = '$order_id'";
        $order=$db->getRow($sql);

        $from_ad=$order['from_ad'];//订单来源
        $agency_id=$order['agency_id'];//获取订单区域
        //查询属性表判断是否有属性
        $sql="SELECT attr_sku FROM ". $ecs->table('goods_attr') ." WHERE goods_id = $goods_id";
        $goods_attr=$db->getOne($sql);
            if($goods_attr){
                $sql="SELECT g.goods_id,g.goods_sku,g.goods_name,g.shop_price,g.market_price,g.promote_price,
                g.promote_start_date,g.promote_end_date,g.preferential_num,g.preferential_price,g.preferential_price2,g.preferential_price5,
                gs.goods_number,ga.attr_value,ga.attr_sku,ga.goods_attr_id ".
                " FROM ".$ecs->table('goods') ." AS g".
                " LEFT JOIN ".$ecs->table('goods_attr') ." AS ga ON g.goods_id = ga.goods_id ".
                " LEFT JOIN ".$ecs->table('goods_stock') ." AS gs ON g.goods_id = gs.goods_id AND ga.goods_attr_id = gs.goods_attr_id ".
                " WHERE g.goods_id = $goods_id AND gs.area_id = $agency_id";
                $goods=$db->getAll($sql);
                //重组数据
                foreach ($goods as $key => $value) {
                    $goods_list['goods_name']=$value['goods_name'];
                    $goods_list['goods_sku']=$value['goods_sku'];
                    if($value['promote_start_date']<time()&&time()<$value['promote_end_date']&&$value['promote_price']>0){
                        $goods_list['shop_price']=$value['promote_price'];
                    }
                    else{
                        $goods_list['shop_price']=$value['shop_price'];
                    }
                    $goods_list['attr_list'][$key]['attr_value']    = $value['attr_value'];
                    $goods_list['attr_list'][$key]['attr_sku']      = $value['attr_sku'];
                    $goods_list['attr_list'][$key]['goods_attr_id'] = $value['goods_attr_id'];
                    /*读取内存库存*/
                    $goods_list['attr_list'][$key]['attr_stock']=$GLOBALS['virtualStock']->selectStock($value['attr_sku']);
                }
                $goods_list['market_price']=$goods['0']['market_price'];
            }
            else{
               $sql="SELECT g.goods_id,g.goods_sku,g.goods_name,g.shop_price,g.market_price,g.promote_price,
                g.promote_start_date,g.promote_end_date,g.preferential_num,g.preferential_price,g.preferential_price2,g.preferential_price5,
                gs.goods_number AS goods_stock".
                " FROM ".$ecs->table('goods') ." AS g".
                " LEFT JOIN ".$ecs->table('goods_stock') ." AS gs ON g.goods_id = gs.goods_id ".
                " WHERE g.goods_id = $goods_id AND gs.area_id = $agency_id";
                $goods_list=$db->getRow($sql);
                /*判断是否为促销价*/
                if($goods_list['promote_start_date']<time()&&time()<$goods_list['promote_end_date']&&$goods_list['promote_price']>0){
                        $goods_list['shop_price']=$goods_list['promote_price'];
                    }
                    else{
                        $goods_list['shop_price']=$goods_list['shop_price'];
                    }
                /*读取内存库存*/
                $goods_list['goods_stock']=$GLOBALS['virtualStock']->selectStock($goods_list['goods_sku']);
            }
            //梯度价处理
            if($goods_list['preferential_price2']<=0){
               $goods_list['preferential_price2']=$goods_list['shop_price'];
            }
            if($goods_list['preferential_price5']<=0){
               $goods_list['preferential_price5']=$goods_list['shop_price'];
            }
         $smarty->assign('from_ad',$from_ad);
         $smarty->assign('goods', $goods_list);
         $return = $smarty->fetch("order/order_goods.htm");
         echo $json->encode($return);
    }
}

/*------------------------------------------------------ */
//-- 合并订单
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'ajax_merge_order')
{
    /* 检查权限 */
    admin_priv('order_os_edit');

    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();

    $from_order_sn = empty($_POST['from_order_sn']) ? '' : json_str_iconv(substr($_POST['from_order_sn'], 1));
    $to_order_sn = empty($_POST['to_order_sn']) ? '' : json_str_iconv(substr($_POST['to_order_sn'], 1));

    $m_result = merge_order($from_order_sn, $to_order_sn);
    $result = array('error'=>0,  'content'=>'');
    if ($m_result === true)
    {
        $result['message'] = $GLOBALS['_LANG']['act_ok'];
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = $m_result;
    }
    die($json->encode($result));
}

/*------------------------------------------------------ */
//-- 删除订单
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'remove_order')
{
    /* 检查权限 */
    admin_priv('order_edit');

    $order_id = intval($_REQUEST['id']);

    /* 检查权限 */
    check_authz_json('order_edit');

    /* 检查订单是否允许删除操作 */
    $order = order_info($order_id);
    $operable_list = operable_list($order);
    if (!isset($operable_list['remove']))
    {
        make_json_error('Hacking attempt');
        exit;
    }

    $GLOBALS['db']->query("DELETE FROM ".$GLOBALS['ecs']->table('order_info'). " WHERE order_id = '$order_id'");
    $GLOBALS['db']->query("DELETE FROM ".$GLOBALS['ecs']->table('order_goods'). " WHERE order_id = '$order_id'");
    $GLOBALS['db']->query("DELETE FROM ".$GLOBALS['ecs']->table('order_action'). " WHERE order_id = '$order_id'");
    $action_array = array('delivery', 'back');
    del_delivery($order_id, $action_array);

    if ($GLOBALS['db'] ->errno() == 0)
    {
        $url = 'order.php?act=query&' . str_replace('act=remove_order', '', $_SERVER['QUERY_STRING']);

        ecs_header("Location: $url\n");
        exit;
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 根据关键字和id搜索用户
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'search_users')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();

    $id_name = empty($_GET['id_name']) ? '' : json_str_iconv(trim($_GET['id_name']));

    $result = array('error'=>0, 'message'=>'', 'content'=>'');
    if ($id_name != '')
    {
        $sql = "SELECT user_id, user_name FROM " . $GLOBALS['ecs']->table('users') .
                " WHERE user_id LIKE '%" . mysql_like_quote($id_name) . "%'" .
                " OR user_name LIKE '%" . mysql_like_quote($id_name) . "%'" .
                " OR email LIKE '%" . mysql_like_quote($id_name) . "%'" .
                " LIMIT 20";
        $res = $GLOBALS['db']->query($sql);

         $result['userlist'] = array();
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
             $result['userlist'][] = array('user_id' => $row['user_id'], 'user_name' => $row['user_name']);
        }
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = 'NO KEYWORDS!';
    }

    die($json->encode($result));
}

/*------------------------------------------------------ */
//-- 根据关键字搜索商品
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'search_goods')
{
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();

    $keyword = empty($_GET['keyword']) ? '' : json_str_iconv(trim($_GET['keyword']));

    $result = array('error'=>0, 'message'=>'', 'content'=>'');

    if ($keyword != '')
    {
        $sql = "SELECT g.goods_id, g.goods_name, g.goods_sku , g.sku FROM " . $GLOBALS['ecs']->table('goods') .' AS g'.
                " WHERE g.is_delete = 0" .
                " AND g.is_on_sale = 1" .
                " AND g.is_alone_sale = 1" .
                " AND (g.goods_id LIKE '%" . mysql_like_quote($keyword) . "%'" .
                " OR g.goods_name LIKE '%" . mysql_like_quote($keyword) . "%'" .
                " OR g.goods_sku LIKE '%" . mysql_like_quote($keyword) . "%')" .
                " OR g.sku LIKE '%" . mysql_like_quote($keyword) . "%'" .
                " LIMIT 20";
        $res = $GLOBALS['db']->query($sql);
        if(!$GLOBALS['db']->getOne($sql)){
            //没有搜索结果则搜索属性产品册号
            $sql = "SELECT g.goods_id, g.goods_name, g.goods_sku , g.sku ,ga.attr_value ,ga.sku as attr_skus FROM " . $GLOBALS['ecs']->table('goods') .' AS g'.
            " LEFT JOIN ".$GLOBALS['ecs']->table('goods_attr').' AS ga '.
            " ON g.goods_id = ga.goods_id ".
            " WHERE g.is_delete = 0" .
            " AND g.is_on_sale = 1" .
            " AND g.is_alone_sale = 1" .
            " AND (g.goods_id LIKE '%" . mysql_like_quote($keyword) . "%'" .
            " OR g.goods_name LIKE '%" . mysql_like_quote($keyword) . "%'" .
            " OR g.goods_sku LIKE '%" . mysql_like_quote($keyword) . "%')" .
            " OR g.sku LIKE '%" . mysql_like_quote($keyword) . "%'" .
            " OR ga.sku LIKE '%" . mysql_like_quote($keyword) . "%'" .
            " LIMIT 20";
            $res = $GLOBALS['db']->query($sql);
        }
        $result['goodslist'] = array();
        while ($row = $GLOBALS['db']->fetchRow($res))
        {
            $result['goodslist'][] = array('goods_id' => $row['goods_id'], 'name' => $row['goods_id'] . '  ' . $row['goods_name'] . '  ' . $row['goods_sku']);
        }
    }
    else
    {
        $result['error'] = 1;
        $result['message'] = 'NO KEYWORDS';
    }
    die($json->encode($result));
}

/*------------------------------------------------------ */
//-- 编辑收货单号
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_invoice_no')
{
    /* 检查权限 */
    check_authz_json('order_edit');

    $no = empty($_POST['val']) ? 'N/A' : json_str_iconv(trim($_POST['val']));
    $no = $no=='N/A' ? '' : $no;
    $order_id = empty($_POST['id']) ? 0 : intval($_POST['id']);

    if ($order_id == 0)
    {
        make_json_error('NO ORDER ID');
        exit;
    }

    $sql = 'UPDATE ' . $GLOBALS['ecs']->table('order_info') . " SET invoice_no='$no' WHERE order_id = '$order_id'";
    if ($GLOBALS['db']->query($sql))
    {
        if (empty($no))
        {
            make_json_result('N/A');
        }
        else
        {
            make_json_result(stripcslashes($no));
        }
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 编辑付款备注
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'edit_pay_note')
{
    /* 检查权限 */
    check_authz_json('order_edit');

    $no = empty($_POST['val']) ? 'N/A' : json_str_iconv(trim($_POST['val']));
    $no = $no=='N/A' ? '' : $no;
    $order_id = empty($_POST['id']) ? 0 : intval($_POST['id']);

    if ($order_id == 0)
    {
        make_json_error('NO ORDER ID');
        exit;
    }

    $sql = 'UPDATE ' . $GLOBALS['ecs']->table('order_info') . " SET pay_note='$no' WHERE order_id = '$order_id'";
    if ($GLOBALS['db']->query($sql))
    {
        if (empty($no))
        {
            make_json_result('N/A');
        }
        else
        {
            make_json_result(stripcslashes($no));
        }
    }
    else
    {
        make_json_error($GLOBALS['db']->errorMsg());
    }
}

/*------------------------------------------------------ */
//-- 获取订单商品信息
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'get_goods_info')
{
    /* 取得订单商品 */
    $order_id = isset($_REQUEST['order_id'])?intval($_REQUEST['order_id']):0;
    if (empty($order_id))
    {
        make_json_response('', 1, $_LANG['error_get_goods_info']);
    }
    $goods_list = array();
    $goods_attr = array();
    $sql = "SELECT o.*, g.goods_thumb, g.goods_number AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name " .
            "FROM " . $ecs->table('order_goods') . " AS o ".
            "LEFT JOIN " . $ecs->table('goods') . " AS g ON o.goods_id = g.goods_id " .
            "LEFT JOIN " . $ecs->table('brand') . " AS b ON g.brand_id = b.brand_id " .
            "WHERE o.order_id = '{$order_id}' ";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res))
    {
        $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
        $row['formated_goods_price']    = price_format($row['goods_price']);
        $_goods_thumb = get_image_path($row['goods_id'], $row['goods_thumb'], true);
        $_goods_thumb = (strpos($_goods_thumb, 'http://') === 0) ? $_goods_thumb : $ecs->url() . $_goods_thumb;
        $row['goods_thumb'] = $_goods_thumb;
        $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组
        $goods_list[] = $row;
    }
    $attr = array();
    $arr  = array();
    foreach ($goods_attr AS $index => $array_val)
    {
        foreach ($array_val AS $value)
        {
            $arr = explode(':', $value);//以 : 号将属性拆开
            $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
        }
    }

    $smarty->assign('goods_attr', $attr);
    $smarty->assign('goods_list', $goods_list);
    $str = $smarty->fetch('order_goods_info.htm');
    $goods[] = array('order_id' => $order_id, 'str' => $str);
    make_json_result($goods);
}
/*------------------------------------------------------ */
//-- 处理后台添加订单数据
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'order_confirm'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    $order_id = $_REQUEST['order_id'];

    $shipping_fee = empty($_REQUEST['shipping_fee'])?0:$_REQUEST['shipping_fee'];
    // 设定末日返回信息
    $return['error'] = 1;
    $return['message'] = "";
    //获取订单区域ID
    $sql="SELECT agency_id,pay_id".
        " FROM ".$GLOBALS['ecs']->table('order_info').
        " WHERE order_id = $order_id ";
    $order_info=$db->getRow($sql); 

    $area_id = $order_info['agency_id'];
    $pay_id = $order_info['pay_id'];
    //获取订单商品
    $sql = "SELECT goods_sku,goods_attr_sku,compose_note,goods_number ,goods_name,goods_attr".
        " FROM ".$GLOBALS['ecs']->table('order_goods').
        " WHERE order_id = $order_id ";
    $order_goods = $db->getAll($sql);
    if(!$order_goods){
        $return['error'] = 0;
        $return['message'] = "订单中没有商品";
        die($json->encode($return));
        exit();
    }
    //循环重组订单商品
    foreach ($order_goods as $key => $value) {
        if($value['goods_attr_sku']){
            $goods[$value['goods_attr_sku']]['goods_number']=empty($goods[$value['goods_attr_sku']]['goods_number'])?$value['goods_number']:$goods[$value['goods_attr_sku']]['goods_number']+$value['goods_number'];
            $goods[$value['goods_attr_sku']]['number'] = $key+1;
        }
        else{
            $goods[$value['goods_sku']]['goods_number']=empty($goods[$value['goods_sku']]['goods_number'])?$value['goods_number']:$goods[$value['goods_sku']]['goods_number']+$value['goods_number'];
            $goods[$value['goods_sku']]['number'] = $key+1;
        }
    }




    //查询判断库存是否大于订单商品
    foreach ($goods as $sku => $number) {
        $sql="SELECT goods_number FROM".$GLOBALS['ecs']->table('goods_stock').
             " WHERE area_id=$area_id AND goods_sku=$sku";
        $stock=$db->getOne($sql);
        if($stock<$number['goods_number']){
            $return['error'] = 0;
            $return['message'] = "商品编号为".$sku.'的商品库存不足';
            $return['number'] = '缺货商品序号为'.$number['number'];
            die($json->encode($return));
            exit();
        }
    }

    //循环商品减少库存
    foreach ($goods as $sku => $number) {
        change_goods_storage($sku,3,-$number['goods_number']);
    }
    // 根据支付方式修改订单状态
    if($pay_id == 3){
        //货到付款
        $sql="UPDATE ".$GLOBALS['ecs']->table('order_info').
         " set order_status = 0,shipping_status = 0,pay_status = 0,shipping_fee = $shipping_fee, order_amount = goods_amount + $shipping_fee".
         " WHERE order_id=$order_id ";
         $db->query($sql);
    }
    if($pay_id == 1){
        //支付宝
        $sql="UPDATE ".$GLOBALS['ecs']->table('order_info').
         " set order_status=1,shipping_status=0,pay_status=2,shipping_fee=$shipping_fee,pay_time=".time().",money_paid=order_amount+$shipping_fee,order_amount=0".
         " WHERE order_id=$order_id ";
        $db->query($sql);
        //更新pay_log为已支付
        $sql ="UPDATE ".$GLOBALS['ecs']->table('pay_log').
         " set is_paid = 1 , order_amount = order_amount + $shipping_fee".
         " WHERE order_id = $order_id ";
        $db->query($sql);
    }

    $order=order_info($order_id);
    order_receive_freeplan($order,1);//订单金额加入奖金池
    // /* 更新 pay_log */
    // update_pay($order_id,$pay_id);
    $return['message'] = "提交订单成功";
    die($json->encode($return));
    exit();
}

/*------------------------------------------------------ */
//-- 处理后台修改订单数据
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'order_edit'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    $order_id=$_REQUEST['order_id'];
    $shipping_fee=empty($_REQUEST['shipping_fee'])?0:$_REQUEST['shipping_fee'];

    // 设定返回信息
    $return['error']=1;
    $return['message']="";
    //获取订单区域ID
    $sql="SELECT agency_id,pay_id".
        " FROM ".$GLOBALS['ecs']->table('order_info').
        " WHERE order_id = $order_id ";
    $order_info=$db->getRow($sql); 
    $area_id=$order_info['agency_id'];
    $pay_id=$order_info['pay_id'];

    // 根据支付方式修改订单状态
    if($pay_id==3){
        //货到付款
        $sql="UPDATE ".$GLOBALS['ecs']->table('order_info').
         " set wangcangstatus=100,order_status=1,shipping_status=0,pay_status=0,shipping_fee=$shipping_fee,order_amount=goods_amount+$shipping_fee".
         " WHERE order_id=$order_id ";
         $db->query($sql);
        require_once(ROOT_PATH . 'includes/lib_wangcang.php');
        vsetpushTrades(array($order_id), $v_data);
    }
    if($pay_id==1){
        //支付宝
        $sql="UPDATE ".$GLOBALS['ecs']->table('order_info').
         " set order_status=0,pay_status=0,shipping_fee=$shipping_fee,order_amount=goods_amount+$shipping_fee-money_paid".
         " WHERE order_id=$order_id ";
        $db->query($sql);
    }
    /* 更新 pay_log */
    update_pay_log($order_id);

    $order=order_info($order_id);
    order_receive_freeplan($order,3);//订单金额加入奖金池
    // update_pay($order_id,$pay_id);
    $return['message']="订单修改成功";
    die($json->encode($return));
    exit();
}

/*------------------------------------------------------ */
//-- AJAX修改地址
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'up_address'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    $obj  = $json->decode($_REQUEST['consignee']);
    $order_id = $_REQUEST['order_id'];
    $province=$obj->province; 
    $city=$obj->city;
    $district=$obj->district;
    $address=$obj->address;
    $mobile=$obj->mobile;
    $consignee=$obj->order_consignee;
    $_SESSION['province']=$province;
    $_SESSION['city']=$city;
    $sql="UPDATE ".$GLOBALS['ecs']->table('order_info').
    " SET province='$province',city='$city',district='$district',address='$address',mobile='$mobile',consignee='$consignee'".
    " WHERE order_id=$order_id ";
    $db->query($sql);
    die($json->encode("更新地址成功"));
}


//处理编辑商品信息
elseif($_REQUEST['act'] == 'edit_goods'){
        // include_once(ROOT_PATH . 'includes/cls_json.php');
        // $json = new JSON();
        $order_id=$_REQUEST['order_id'];//获取ID
        $sql="SELECT order_sn, order_status, shipping_status, wangcangstatus FROM ".$GLOBALS['ecs']->table('order_info').
            " WHERE order_id=$order_id";
        $status=$db->getRow($sql);//获取订单状态
        $order_sn = $status['order_sn'];
        $shipping_status=$status['shipping_status'];//物流状态
        $order_status=$status['order_status'];//订单状态
        if($order_status == 5||$shipping_status==1||$shipping_status==2){
            $links[] = array('href' => 'order.php?act=info&order_id='.$order_id, 'text' => "订单已经发货无法修改点击返回");
            sys_msg("已经发货不能修改", 100, $links);
        }
        elseif($order_status ==3||$order_status ==2){
            //添加中的订单处理
             ecs_header("Location: order.php?act=add&order_id=".$order_id."&step=goods\n");
        }
        else{
            //将订单状态修改为编辑中
            $sql="UPDATE ".$GLOBALS['ecs']->table('order_info').
                " set order_status = 4, shipping_status = 0, pay_status = 0, pay_time = 0".
                " WHERE order_id=$order_id";
            $db->query($sql);
            /* 作废网仓订单 */
            if(!empty($order_sn) && $status['wangcangstatus'] > 0){
                require_once(ROOT_PATH . 'includes/lib_wangcang.php');
                $data = vgetcancelTrade(array($order_sn), $v_data);
                if(!empty($data)){
                    foreach ($data as $key => $value) {
                        if(!empty($value['data']['flag']) && $value['data']['flag'] == 'true'){
                            $sql = "UPDATE " . $ecs->table('order_info') . " SET wangcangstatus = 0 WHERE order_sn = $order_sn";
                            $db->query($sql);
                        }elseif(!empty($value['errorCode']) && $value['errorCode'] == '190'){
                            $sql = "UPDATE " . $ecs->table('order_info') . " SET wangcangstatus = 0 WHERE order_sn = $order_sn";
                            $db->query($sql);
                        }
                    }
                }
            }
            ecs_header("Location: order.php?act=edit&order_id=".$order_id."&step=goods\n");
        }
}
//AJAX标记补发商品
elseif($_REQUEST['act'] == 'remedy_goods'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    $rec_id=!empty($_REQUEST['rec_id'])?$_REQUEST['rec_id']:'';
    $order_id = !empty($_REQUEST['order_id'])?$_REQUEST['order_id']:'';
    //更新订单数据表
    $sql =  " UPDATE ".$ecs->table('order_goods') .
            " set extension_code = 'again' ,    goods_price = '0' ".
            " WHERE rec_id = $rec_id";
    $db->query($sql);
    //更新价格
    $goods_amount = order_amount($order_id);
    update_order($order_id, array('goods_amount' => $goods_amount));
    update_order_amount($order_id);

    /* 更新 pay_log */
    update_pay_log($order_id);


    die($json->encode(1));
}
//AJAX生成补发单
elseif($_REQUEST['act'] == 'order_remedy'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    $order_id=!empty($_REQUEST['order_id'])?$_REQUEST['order_id']:'';
    $order_sn_old = !empty($_REQUEST['order_sn_old'])?$_REQUEST['order_sn_old']:'';
    $remedy_type = !empty($_REQUEST['remedy_type'])?$_REQUEST['remedy_type']:'';

    $return['error']="1";
    $return['content']="";



    //整理补发单信息
    $sql = "SELECT order_sn FROM ".$ecs->table('order_info') ." WHERE order_id = $order_id ";
    $order_sn =$db->getOne($sql); //补发订单号
    $sql = "SELECT order_id FROM ".$ecs->table('order_info') ." WHERE order_sn = $order_sn_old ";
    $order_id_old =$db->getOne($sql);//出错订单ID
    if(empty($order_id_old)){
        $return['error']="2";
        $return['content']="你输入的订单号不存在";
        die($json->encode($return));
    }

    //查询补发商品商品
    $sql =  " SELECT goods_sku , goods_attr_sku , goods_number , goods_name ,goods_attr,goods_id  ".
            " FROM ".$ecs->table('order_goods').
            " WHERE order_id = $order_id AND extension_code = 'again' ";
    $order_goods = $db->getAll($sql);
    if(empty($order_goods)){
        $return['error']="2";
        $return['content']="请标记补发商品";
        die($json->encode($return));
    }
    //查询补发商品与出错商品是否一致
    foreach ($order_goods as $key => $value) {
    $sql =  " SELECT goods_price ".
            " FROM ".$ecs->table('order_goods').
            " WHERE order_id = $order_id_old AND goods_id = '$value[goods_id]' AND goods_sku = '$value[goods_sku]' AND goods_attr_sku = '$value[goods_attr_sku]' ";
    $is_goods = $db->getOne($sql); 
    if(empty($is_goods)){
        $return['error']="2";
        $return['content']="补发商品与出错商品不一致";
        die($json->encode($return));
    }


    }



    $order_remedy_info  = array(
            'order_sn'      => $order_sn, 
            'order_sn_old'  => $order_sn_old,
            'remedy_type'   => $remedy_type,
            'add_time'      => time() ,
            'user_name'     =>$_SESSION['admin_name'],
        );
    $db->autoExecute($ecs->table('order_remedy_info'), $order_remedy_info, 'INSERT', '', 'SILENT'); 
    $remedy_id = $db->insert_id();//补发单ID   

    //获取商品价格并写入数据表
    foreach ($order_goods as $key => $value) {
    $sql =  " SELECT goods_price ".
            " FROM ".$ecs->table('order_goods').
            " WHERE order_id = $order_id_old AND goods_id = '$value[goods_id]' AND goods_sku = '$value[goods_sku]' AND goods_attr_sku = '$value[goods_attr_sku]' ";

    $goods_price = $db->getOne($sql); 

    $remedy_goods =  "";
    $remedy_goods = array(
        'remedy_id'     => $remedy_id,
        'goods_id'      => $value['goods_id'],
        'goods_name'    => $value['goods_name'],
        'goods_attr'    => $value['goods_attr'],
        'goods_number'  => $value['goods_number'],
        'goods_price'   => $goods_price,
         );
    $db->autoExecute($ecs->table('order_remedy_goods'), $remedy_goods, 'INSERT', '', 'SILENT'); 
    }







    $return['content']="生成补发单成功";
    die($json->encode($return));
}

//AJAX查询改订单是否存在部分单
elseif($_REQUEST['act'] == 'is_remedy'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    $return['error']="1";
    $return['content']="";
    $order_sn_old = !empty($_REQUEST['order_sn_old'])?$_REQUEST['order_sn_old']:'';
    $sql = "SELECT remedy_id FROM ".$ecs->table('order_remedy_info')." WHERE order_sn_old = $order_sn_old ";
    $remedy_id = $db->getOne($sql);

    if(empty($remedy_id)){


    die($json->encode($return));
    }
    else{
    $return['error']="2";
    $return['content']="改订单号已存在补发单是否继续添加补发单";
    die($json->encode($return));
    }


}


/**
 * 取得状态列表
 * @param   string  $type   类型：all | order | shipping | payment
 */
function get_status_list($type = 'all')
{
    global $_LANG;

    $list = array();

    if ($type == 'all' || $type == 'order')
    {
        $pre = $type == 'all' ? 'os_' : '';
        foreach ($_LANG['os'] AS $key => $value)
        {
            $list[$pre . $key] = $value;
        }
    }

    if ($type == 'all' || $type == 'shipping')
    {
        $pre = $type == 'all' ? 'ss_' : '';
        foreach ($_LANG['ss'] AS $key => $value)
        {
            $list[$pre . $key] = $value;
        }
    }

    if ($type == 'all' || $type == 'payment')
    {
        $pre = $type == 'all' ? 'ps_' : '';
        foreach ($_LANG['ps'] AS $key => $value)
        {
            $list[$pre . $key] = $value;
        }
    }
    return $list;
}

/**
 * 退回余额、积分、红包（取消、无效、退货时），把订单使用余额、积分、红包设为0
 * @param   array   $order  订单信息
 */
function return_user_surplus_integral_bonus($order)
{
    /* 处理余额、积分、红包 */
    if ($order['user_id'] > 0 && $order['surplus'] > 0)
    {
        $surplus = $order['money_paid'] < 0 ? $order['surplus'] + $order['money_paid'] : $order['surplus'];
        log_account_change($order['user_id'], $surplus, 0, 0, 0, sprintf($GLOBALS['_LANG']['return_order_surplus'], $order['order_sn']));
        $GLOBALS['db']->query("UPDATE ". $GLOBALS['ecs']->table('order_info') . " SET `order_amount` = '0' WHERE `order_id` =". $order['order_id']);
    }

    if ($order['user_id'] > 0 && $order['integral'] > 0)
    {
        log_account_change($order['user_id'], 0, 0, 0, $order['integral'], sprintf($GLOBALS['_LANG']['return_order_integral'], $order['order_sn']));
    }

    if ($order['bonus_id'] > 0)
    {
        unuse_bonus($order['bonus_id']);
    }

    /* 修改订单 */
    $arr = array(
        'bonus_id'  => 0,
        'bonus'     => 0,
        'integral'  => 0,
        'integral_money'    => 0,
        'surplus'   => 0
    );
    update_order($order['order_id'], $arr);
}

/**
 * 更新订单总金额
 * @param   int     $order_id   订单id
 * @return  bool
 */
function update_order_amount($order_id)
{
    include_once(ROOT_PATH . 'includes/lib_order.php');
    //更新订单总金额
    $sql = "UPDATE " . $GLOBALS['ecs']->table('order_info') .
            " SET order_amount = " . order_due_field() .
            " WHERE order_id = '$order_id' LIMIT 1";

    return $GLOBALS['db']->query($sql);
}

/**
 * 返回某个订单可执行的操作列表，包括权限判断
 * @param   array   $order      订单信息 order_status, shipping_status, pay_status
 * @param   bool    $is_cod     支付方式是否货到付款
 * @return  array   可执行的操作  confirm, pay, unpay, prepare, ship, unship, receive, cancel, invalid, return, drop
 * 格式 array('confirm' => true, 'pay' => true)
 */
function operable_list($order)
{
    /* 取得订单状态、发货状态、付款状态 */
    $os = $order['order_status'];
    $ss = $order['shipping_status'];
    $ps = $order['pay_status'];
    /* 取得订单操作权限 */
    $actions = $_SESSION['action_list'];
    if ($actions == 'all')
    {
        $priv_list  = array('os' => true, 'ss' => true, 'ps' => true, 'edit' => true);
    }
    else
    {
        $actions    = ',' . $actions . ',';
        $priv_list  = array(
            'os'    => strpos($actions, ',order_os_edit,') !== false,
            'ss'    => strpos($actions, ',order_ss_edit,') !== false,
            'ps'    => strpos($actions, ',order_ps_edit,') !== false,
            'edit'  => strpos($actions, ',order_edit,') !== false
        );
    }

    /* 取得订单支付方式是否货到付款 */
    $payment = payment_info($order['pay_id']);
    $is_cod  = $payment['is_cod'] == 1;

    /* 根据状态返回可执行操作 */
    $list = array();
    if (OS_UNCONFIRMED == $os)
    {
        /* 状态：未确认 => 未付款、未发货 */
        if ($priv_list['os'])
        {
            $list['confirm']    = true; // 确认
            // $list['invalid']    = true; // 无效
            $list['cancel']     = true; // 取消
            if ($is_cod)
            {
                /* 货到付款 */
                if ($priv_list['ss'])
                {
                    $list['prepare'] = true; // 配货
                    // $list['split'] = true; // 分单
                }
            }
            else
            {
                /* 不是货到付款 */
                if ($priv_list['ps'])
                {
                    $list['pay'] = true;  // 付款
                }
            }
        }
    }
    elseif (OS_CONFIRMED == $os || OS_SPLITED == $os || OS_SPLITING_PART == $os)
    {
        /* 状态：已确认 */
        if (PS_UNPAYED == $ps)
        {
            /* 状态：已确认、未付款 */
            if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
            {
                /* 状态：已确认、未付款、未发货（或配货中） */
                if ($priv_list['os'])
                {
                    $list['cancel'] = true; // 取消
                    // $list['invalid'] = true; // 无效
                }
                if ($is_cod)
                {
                    /* 货到付款 */
                    if ($priv_list['ss'])
                    {
                        if (SS_UNSHIPPED == $ss)
                        {
                            $list['prepare'] = true; // 配货
                        }
                        // $list['split'] = true; // 分单
                    }
                }
                else
                {
                    /* 不是货到付款 */
                    if ($priv_list['ps'])
                    {
                        $list['pay'] = true; // 付款
                    }
                }
            }
            /* 状态：已确认、未付款、发货中 */
            elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
            {
                // 部分分单
                if (OS_SPLITING_PART == $os)
                {
                    // $list['split'] = true; // 分单
                }
                $list['to_delivery'] = true; // 去发货
            }
            else
            {
                /* 状态：已确认、未付款、已发货或已收货 => 货到付款 */
                if ($priv_list['ps'])
                {
                    $list['pay'] = true; // 付款
                }
                if ($priv_list['ss'])
                {
                    if (SS_SHIPPED == $ss)
                    {
                        $list['receive'] = true; // 收货确认
                    }
                    $list['unship'] = true; // 设为未发货
                    if ($priv_list['os'])
                    {
                        $list['return'] = true; // 退货
                    }
                }
            }
        }
        else
        {
            /* 状态：已确认、已付款和付款中 */
            if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
            {
                /* 状态：已确认、已付款和付款中、未发货（配货中） => 不是货到付款 */
                if ($priv_list['ss'])
                {
                    if (SS_UNSHIPPED == $ss)
                    {
                        $list['prepare'] = true; // 配货
                    }
                    // $list['split'] = true; // 分单
                }
                if ($priv_list['ps'])
                {
                    $list['unpay'] = true; // 设为未付款
                    if ($priv_list['os'])
                    {
                        $list['cancel'] = true; // 取消
                    }
                }
            }
            /* 状态：已确认、未付款、发货中 */
            elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
            {
                // 部分分单
                if (OS_SPLITING_PART == $os)
                {
                    $list['split'] = true; // 分单
                }
                $list['to_delivery'] = true; // 去发货
            }
            else
            {
                /* 状态：已确认、已付款和付款中、已发货或已收货 */
                if ($priv_list['ss'])
                {
                    if (SS_SHIPPED == $ss)
                    {
                        $list['receive'] = true; // 收货确认
                    }
                    if (!$is_cod)
                    {
                        $list['unship'] = true; // 设为未发货
                    }
                }
                if ($priv_list['ps'] && $is_cod)
                {
                    $list['unpay']  = true; // 设为未付款
                }
                if ($priv_list['os'] && $priv_list['ss'] && $priv_list['ps'])
                {
                    $list['return'] = true; // 退货（包括退款）
                }
            }
        }
    }
    elseif (OS_CANCELED == $os)
    {
        /* 状态：取消 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
        }
        if ($priv_list['edit'])
        {
            $list['remove'] = true;
        }
    }
    elseif (OS_INVALID == $os)
    {
        /* 状态：无效 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
        }
        if ($priv_list['edit'])
        {
            $list['remove'] = true;
        }
    }
    elseif (OS_RETURNED == $os)
    {
        /* 状态：退货 */
        if ($priv_list['os'])
        {
            $list['confirm'] = true;
        }
    }

    /* 修正发货操作 */
    if (!empty($list['split']))
    {

            $list['return'] = true; // 退货（包括退款）
            unset($list['cancel']); // 取消
    }

    /* 售后 */
    $list['after_service'] = true;

    return $list;
}

/**
 * 处理编辑订单时订单金额变动
 * @param   array   $order  订单信息
 * @param   array   $msgs   提示信息
 * @param   array   $links  链接信息
 */
function handle_order_money_change($order, &$msgs, &$links)
{
    $order_id = $order['order_id'];
    if ($order['pay_status'] == PS_PAYED || $order['pay_status'] == PS_PAYING)
    {
        /* 应付款金额 */
        $money_dues = $order['order_amount'];
        if ($money_dues > 0)
        {
            /* 修改订单为未付款 */
            update_order($order_id, array('pay_status' => PS_UNPAYED, 'pay_time' => 0));
            $msgs[]     = $GLOBALS['_LANG']['amount_increase'];
            $links[]    = array('text' => $GLOBALS['_LANG']['order_info'], 'href' => 'order.php?act=info&order_id=' . $order_id);
        }
        elseif ($money_dues < 0)
        {
            $anonymous  = $order['user_id'] > 0 ? 0 : 1;
            $msgs[]     = $GLOBALS['_LANG']['amount_decrease'];
            $links[]    = array('text' => $GLOBALS['_LANG']['refund'], 'href' => 'order.php?act=process&func=load_refund&anonymous=' .
                $anonymous . '&order_id=' . $order_id . '&refund_amount=' . abs($money_dues));
        }
    }
}

/**
 *  获取订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list()
{  
    $result = get_filter();
   
    if ($result === false)
    {
        /* 过滤信息 */
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['consignee'] = json_str_iconv($_REQUEST['consignee']);
            //$_REQUEST['address'] = json_str_iconv($_REQUEST['address']);
        }
        $filter['consignee'] = empty($_REQUEST['consignee']) ? '' : trim($_REQUEST['consignee']);
        $filter['email'] = empty($_REQUEST['email']) ? '' : trim($_REQUEST['email']);
        $filter['address'] = empty($_REQUEST['address']) ? '' : trim($_REQUEST['address']);
        $filter['zipcode'] = empty($_REQUEST['zipcode']) ? '' : trim($_REQUEST['zipcode']);
        $filter['tel'] = empty($_REQUEST['tel']) ? '' : trim($_REQUEST['tel']);
        $filter['mobile'] = empty($_REQUEST['mobile']) ? 0 : intval($_REQUEST['mobile']);
        $filter['country'] = empty($_REQUEST['country']) ? 0 : intval($_REQUEST['country']);
        $filter['province'] = empty($_REQUEST['province']) ? 0 : intval($_REQUEST['province']);
        $filter['city'] = empty($_REQUEST['city']) ? 0 : intval($_REQUEST['city']);
        $filter['district'] = empty($_REQUEST['district']) ? 0 : intval($_REQUEST['district']);
        $filter['shipping_id'] = empty($_REQUEST['shipping_id']) ? 0 : intval($_REQUEST['shipping_id']);
        $filter['pay_id'] = empty($_REQUEST['pay_id']) ? 0 : intval($_REQUEST['pay_id']);
        $filter['order_status'] = isset($_REQUEST['order_status']) ? intval($_REQUEST['order_status']) : -1;
        $filter['shipping_status'] = isset($_REQUEST['shipping_status']) ? intval($_REQUEST['shipping_status']) : -1;
        $filter['pay_status'] = isset($_REQUEST['pay_status']) ? intval($_REQUEST['pay_status']) : -1;
        $filter['user_id'] = empty($_REQUEST['user_id']) ? 0 : intval($_REQUEST['user_id']);
        $filter['user_name'] = empty($_REQUEST['user_name']) ? '' : trim($_REQUEST['user_name']);
        $filter['composite_status'] = isset($_REQUEST['composite_status']) ? intval($_REQUEST['composite_status']) : -1;
        $filter['group_buy_id'] = isset($_REQUEST['group_buy_id']) ? intval($_REQUEST['group_buy_id']) : 0;
        $filter['invoice_no'] = isset($_REQUEST['invoice_no']) ? intval($_REQUEST['invoice_no']) : 0;
        $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'add_time' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['cancel_list']= empty($_REQUEST['cancel_list']) ? '' : trim($_REQUEST['cancel_list']);//待取消筛选
        $filter['start_time'] = empty($_REQUEST['start_time']) ? '' : (strpos($_REQUEST['start_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_time']) : $_REQUEST['start_time']);
        $filter['end_time'] = empty($_REQUEST['end_time']) ? '' : (strpos($_REQUEST['end_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_time']) : $_REQUEST['end_time']);

        $where = 'WHERE 1 ';
        if($filter['cancel_list']){
            $time=time();
           $where .= " AND ($time-o.add_time)>86400 AND pay_time = 0 AND pay_id = 1 AND order_status !=2 AND  order_status !=3 and pay_status=0";
        }




        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['invoice_no'])
        {
            $where .= " AND o.invoice_no LIKE '%" . mysql_like_quote($filter['invoice_no']) . "%'";
        }
        if ($filter['consignee'])
        {
            $where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
        }
        if ($filter['email'])
        {
            $where .= " AND o.email LIKE '%" . mysql_like_quote($filter['email']) . "%'";
        }
        if ($filter['address'])
        {
            $where .= " AND o.address LIKE '%" . mysql_like_quote($filter['address']) . "%'";
        }
        if ($filter['zipcode'])
        {
            $where .= " AND o.zipcode LIKE '%" . mysql_like_quote($filter['zipcode']) . "%'";
        }
        if ($filter['tel'])
        {
            $where .= " AND o.tel LIKE '%" . mysql_like_quote($filter['tel']) . "%'";
        }
        if ($filter['mobile'])
        {
            $where .= " AND o.mobile LIKE '%" .mysql_like_quote($filter['mobile']) . "%'";
        }
        if ($filter['country'])
        {
            $where .= " AND o.country = '$filter[country]'";
        }
        if ($filter['province'])
        {
            $where .= " AND o.province = '$filter[province]'";
        }
        if ($filter['city'])
        {
            $where .= " AND o.city = '$filter[city]'";
        }
        if ($filter['district'])
        {
            $where .= " AND o.district = '$filter[district]'";
        }
        if ($filter['shipping_id'])
        {
            $where .= " AND o.shipping_id  = '$filter[shipping_id]'";
        }
        if ($filter['pay_id'])
        {
            $where .= " AND o.pay_id  = '$filter[pay_id]'";
        }
        if ($filter['order_status'] != -1)
        {
            $where .= " AND o.order_status  = '$filter[order_status]'";
        }
        if ($filter['shipping_status'] != -1)
        {
            $where .= " AND o.shipping_status = '$filter[shipping_status]'";
        }
        if ($filter['pay_status'] != -1)
        {
            $where .= " AND o.pay_status = '$filter[pay_status]'";
        }
        if ($filter['user_id'])
        {
            $where .= " AND o.user_id = '$filter[user_id]'";
        }
        if ($filter['user_name'])
        {
            $where .= " AND u.user_name LIKE '%" . mysql_like_quote($filter['user_name']) . "%'";
        }
        if ($filter['start_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_time]'";
        }
        if ($filter['end_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_time]'";
        }

        //综合状态
        switch($filter['composite_status'])
        {
            case CS_AWAIT_PAY :
                $where .= order_query_sql('await_pay');
                break;

            case CS_AWAIT_SHIP :
                $where .= order_query_sql('await_ship');
                break;

            case CS_FINISHED :
                $where .= order_query_sql('finished');
                break;

            case PS_PAYING :
                if ($filter['composite_status'] != -1)
                {
                    $where .= " AND o.pay_status = '$filter[composite_status]' ";
                }
                break;
            case OS_SHIPPED_PART :
                if ($filter['composite_status'] != -1)
                {
                    $where .= " AND o.shipping_status  = '$filter[composite_status]'-2 ";
                }
                break;
            default:
                if ($filter['composite_status'] != -1)
                {
                    $where .= " AND o.order_status = '$filter[composite_status]' ";
                }
        }

        /* 团购订单 */
        if ($filter['group_buy_id'])
        {
            $where .= " AND o.extension_code = 'group_buy' AND o.extension_id = '$filter[group_buy_id]' ";
        }

        /* 如果管理员属于某个办事处，只列出这个办事处管辖的订单 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);
        if ($agency_id > 0)
        {
            $where .= " AND o.agency_id = '$agency_id' ";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

        /* 记录总数 */
        if ($filter['user_name'])
        {
            $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " AS o ,".
                   $GLOBALS['ecs']->table('users') . " AS u " . $where;
        }
        else
        {
            $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " AS o ". $where;
        }

        $filter['record_count']   = $GLOBALS['db']->getOne($sql);
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

        /* 查询 */
        $sql = "SELECT o.order_id,o.join_id, o.order_sn, o.add_time, o.order_status, o.shipping_status, o.order_amount, o.money_paid, o.province, o.city, o.district, o.shipping_fee, uf.idcardnumber,o.pay_name,o.wangcangstatus, " .
                    "o.pay_status, o.consignee, o.address, o.email, o.tel, o.extension_code, o.extension_id, " .
                    "(" . order_amount_field('o.') . ") AS total_fee, " .
                    " IFNULL(u.user_name, '" .$GLOBALS['_LANG']['anonymous']. "') AS buyer, ".
                    " (SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE user_id = o.user_id AND (order_status != 2 OR order_status != 3) ) AS user_order_number ".
                " FROM " . $GLOBALS['ecs']->table('order_info') . " AS o " .
                " LEFT JOIN " .$GLOBALS['ecs']->table('user_freeplan'). " AS uf ON uf.user_id=o.user_id ".
                " LEFT JOIN " .$GLOBALS['ecs']->table('users'). " AS u ON u.user_id=o.user_id ". $where .
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

        foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
        {
            $filter[$val] = stripslashes($filter[$val]);
        }
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $row = $GLOBALS['db']->getAll($sql);
    require_once(ROOT_PATH . 'languages/zh_cn/wangcang.php');
    /* 格式话数据 */
    foreach ($row AS $key => $value)
    {
        $row[$key]['isjoin'] = $value['join_id']>0 ? '<span style="color:red">已合单,</span>' : '';
        $row[$key]['formated_order_amount'] = price_format($value['order_amount']);
        $row[$key]['formated_money_paid'] = price_format($value['money_paid']);
        $row[$key]['formated_total_fee'] = price_format($value['total_fee']);
        $row[$key]['formated_shipping_fee'] = price_format($value['shipping_fee']);
        $row[$key]['short_order_time'] = local_date('m-d H:i', $value['add_time']);
        $row[$key]['province'] = selectaddress($value['province']);
        $row[$key]['city'] = selectaddress($value['city']);
        $row[$key]['district'] = selectaddress($value['district']);
        if($value['wangcangstatus']){
            $row[$key]['wangcangstatus'] = !empty($_LANG['status'][$value['wangcangstatus']])?$_LANG['status'][$value['wangcangstatus']]:'未知状态';
        }
        if ($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED)
        {
            /* 如果该订单为无效或取消则显示删除链接 */
            $row[$key]['can_remove'] = 1;
        }
        else
        {
            $row[$key]['can_remove'] = 0;
        }
    }
    $arr = array('orders' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
    return $arr;
}

/**
 *  获取售后订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list_bought()
{  
    $result = get_filter();
   
    if ($result === false)
    {
        /* 过滤信息 */
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['consignee'] = json_str_iconv($_REQUEST['consignee']);
            //$_REQUEST['address'] = json_str_iconv($_REQUEST['address']);
        }
        $filter['cause'] = empty($_REQUEST['cause']) ? '0' : trim($_REQUEST['cause']);
        $filter['result'] = empty($_REQUEST['result']) ? '0' : trim($_REQUEST['result']);
        $filter['area_id'] = empty($_REQUEST['area_id']) ? '' : trim($_REQUEST['area_id']);

        $filter['start_time'] = empty($_REQUEST['start_time']) ? '' : (strpos($_REQUEST['start_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_time']) : $_REQUEST['start_time']);
        $filter['end_time'] = empty($_REQUEST['end_time']) ? '' : (strpos($_REQUEST['end_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_time']) : $_REQUEST['end_time']);



        $where = 'WHERE 1 ';
        if ($filter['cause'])
        {   
            if($filter['cause']==8){
                $filter['cause']=0;
            }
            $where .= " AND oa.cause = '".$filter['cause']."'";
        }

        if ($filter['result'])
        {
            if($filter['result']==8){
                $filter['result']=0;
            }
            $where .= " AND oa.result = '".$filter['result']."'";
        }
        if ($filter['area_id'])
        {
            $where .= " AND o.agency_id = '".$filter['area_id']."'";
        }
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['consignee'])
        {
            $where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
        }
    

    
        if ($filter['start_time'])
        {
            $where .= " AND oa.log_time >= '$filter[start_time]'";
        }
        if ($filter['end_time'])
        {
            $where .= " AND oa.log_time <= '$filter[end_time]'";
        }





        /* 如果管理员属于某个办事处，只列出这个办事处管辖的订单 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);
        if ($agency_id > 0)
        {
            $where .= " AND o.agency_id = '$agency_id' ";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

        $where=$where."AND oa.action_note LIKE  '%售后%'";
        /* 查询 */
        $sql = "SELECT o.order_id,o.join_id, o.order_sn, o.add_time, o.order_status, o.shipping_status, o.order_amount, o.money_paid, o.province, o.city, o.district, o.shipping_fee, " .
                    "o.pay_status, o.consignee, o.address, o.email, o.tel, o.extension_code, o.extension_id, oa.action_note,oa.log_time," .
                    "(" . order_amount_field('o.') . ") AS total_fee, " .
                    " IFNULL(u.user_name, '" .$GLOBALS['_LANG']['anonymous']. "') AS buyer ".
                " FROM " .
                " ( SELECT * FROM ".$GLOBALS['ecs']->table('order_action') ."  ORDER BY log_time DESC ) ".
                " oa " .
                " LEFT JOIN " .$GLOBALS['ecs']->table('order_info'). " AS o ON oa.order_id=o.order_id ".
                " LEFT JOIN " .$GLOBALS['ecs']->table('users'). " AS u ON u.user_id=o.user_id ". 
                $where . 
                " GROUP BY o.order_id".
                " ORDER BY oa.log_time DESC  ";
        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;//总数
        $sql=$sql." LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
        foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
        {
            $filter[$val] = stripslashes($filter[$val]);
        }
        set_filter($filter, $sql);
    }
    else
    {   
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $row = $GLOBALS['db']->getAll($sql);
    
    /* 格式话数据 */
    foreach ($row AS $key => $value)
    {
        $row[$key]['isjoin'] = $value['join_id']>0 ? '<span style="color:red">已合单,</span>' : '';
        $row[$key]['formated_order_amount'] = price_format($value['order_amount']);
        $row[$key]['formated_money_paid'] = price_format($value['money_paid']);
        $row[$key]['formated_total_fee'] = price_format($value['total_fee']);
        $row[$key]['formated_shipping_fee'] = price_format($value['shipping_fee']);
        $row[$key]['short_order_time'] = local_date('m-d H:i', $value['add_time']);
        $row[$key]['province'] = selectaddress($value['province']);
        $row[$key]['city'] = selectaddress($value['city']);
        $row[$key]['district'] = selectaddress($value['district']); 
        $row[$key]['log_time'] =date('Y-m-d H:i:s',$value['log_time']);
        if ($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED)
        {
            /* 如果该订单为无效或取消则显示删除链接 */
            $row[$key]['can_remove'] = 1;
        }
        else
        {
            $row[$key]['can_remove'] = 0;
        }
    }
    $arr = array('orders' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
    return $arr;
}




/**
 *  获取订单导出数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list_export()
{  
    /* 过滤信息 */
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['consignee'] = json_str_iconv($_REQUEST['consignee']);
            //$_REQUEST['address'] = json_str_iconv($_REQUEST['address']);
        }
        $filter['buyer'] = empty($_REQUEST['buyer']) ? '' : trim($_REQUEST['buyer']);
        $filter['status'] = empty($_REQUEST['status']) ? '0' : trim($_REQUEST['status']);
        $filter['start_time'] = empty($_REQUEST['start_time']) ? '' : (strpos($_REQUEST['start_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_time']) : $_REQUEST['start_time']);
        $filter['end_time'] = empty($_REQUEST['end_time']) ? '' : (strpos($_REQUEST['end_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_time']) : $_REQUEST['end_time']);

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['consignee'])
        {
            $where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
        }
        if ($filter['start_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_time]' ";
        }
        if ($filter['end_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_time]' ";
        }
        if ($filter['status'] > 0)
        {
            $where .= " AND o.order_status = '5' AND o.shipping_status = '2' AND o.pay_status = '2' ";
        }
        /* 查询 */
        $sql = "SELECT o.order_id, o.order_sn, o.add_time, o.consignee, o.address, o.pay_name, o.order_amount, o.goods_amount, o.shipping_fee, o.order_status, o.shipping_status, o.pay_status, o.wangcangstatus, (" . order_amount_field('o.') . ") AS total_fee, " .
                    " IFNULL(u.user_name, '" .$GLOBALS['_LANG']['anonymous']. "') AS buyer ".
                " FROM " . 
                $GLOBALS['ecs']->table('order_info').
                " AS o " . 
                " LEFT JOIN " .$GLOBALS['ecs']->table('users'). " AS u ON u.user_id=o.user_id ". 
                $where . 
                (empty($filter['buyer'])?'':' AND u.user_name = ' . "'$filter[buyer]' AND (o.order_status = 1 OR o.order_status = 5)") .
                " GROUP BY o.order_id".
                " ORDER BY o.add_time DESC  ";
        $row = $GLOBALS['db']->getAll($sql);
            /* 格式化 */
    foreach ($row AS $key => $value)
    {
        $row[$key]['add_time'] =date('Y-m-d H:i:s',$value['add_time']);
    }

    return $row;
}







/**
 *  获取售后订单导出数据
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list_bought_export()
{  

        /* 过滤信息 */
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['consignee'] = json_str_iconv($_REQUEST['consignee']);
            //$_REQUEST['address'] = json_str_iconv($_REQUEST['address']);
        }
        $filter['cause'] = empty($_REQUEST['cause']) ? '0' : trim($_REQUEST['cause']);
        $filter['result'] = empty($_REQUEST['result']) ? '0' : trim($_REQUEST['result']);
        $filter['area_id'] = empty($_REQUEST['area_id']) ? '' : trim($_REQUEST['area_id']);

        $filter['start_time'] = empty($_REQUEST['start_time']) ? '' : (strpos($_REQUEST['start_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_time']) : $_REQUEST['start_time']);
        $filter['end_time'] = empty($_REQUEST['end_time']) ? '' : (strpos($_REQUEST['end_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_time']) : $_REQUEST['end_time']);



        $where = 'WHERE 1 ';
        if ($filter['cause'])
        {   
            if($filter['cause']==8){
                $filter['cause']=0;
            }
            $where .= " AND oa.cause = '".$filter['cause']."'";
        }

        if ($filter['result'])
        {
            if($filter['result']==8){
                $filter['result']=0;
            }
            $where .= " AND oa.result = '".$filter['result']."'";
        }
        if ($filter['area_id'])
        {
            $where .= " AND o.agency_id = '".$filter['area_id']."'";
        }
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['consignee'])
        {
            $where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
        }
        if ($filter['start_time'])
        {
            $where .= " AND oa.log_time >= '$filter[start_time]'";
        }
        if ($filter['end_time'])
        {
            $where .= " AND oa.log_time <= '$filter[end_time]'";
        }
        $where=$where."AND oa.action_note LIKE  '%售后%'";
        /* 查询 */
        $sql = "SELECT o.order_id, o.order_sn, o.add_time, " .
                    " o.consignee, o.address,  oa.action_note,oa.log_time," .

                    " IFNULL(u.user_name, '" .$GLOBALS['_LANG']['anonymous']. "') AS buyer ".
                " FROM " .
                $GLOBALS['ecs']->table('order_action').
                " AS oa " .
                " LEFT JOIN " .$GLOBALS['ecs']->table('order_info'). " AS o ON oa.order_id=o.order_id ".
                " LEFT JOIN " .$GLOBALS['ecs']->table('users'). " AS u ON u.user_id=o.user_id ". 
                $where . 
                " GROUP BY o.order_id".
                " ORDER BY oa.log_time DESC  ";

        $row = $GLOBALS['db']->getAll($sql);
            /* 格式化 */
    foreach ($row AS $key => $value)
    {
        $row[$key]['add_time'] =date('Y-m-d H:i:s',$value['add_time']);
        $row[$key]['log_time'] =date('Y-m-d H:i:s',$value['log_time']);
    }

    return $row;
}











/**
 * 更新订单对应的 pay_log
 * 如果未支付，修改支付金额；否则，生成新的支付log
 * @param   int     $order_id   订单id
 */
function update_pay_log($order_id)
{
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT order_amount FROM " . $GLOBALS['ecs']->table('order_info') .
                " WHERE order_id = '$order_id'";
        $order_amount = $GLOBALS['db']->getOne($sql);
        if (!is_null($order_amount))
        {
            $sql = "SELECT log_id FROM " . $GLOBALS['ecs']->table('pay_log') .
                    " WHERE order_id = '$order_id'" .
                    " AND order_type = '" . PAY_ORDER . "'" .
                    " AND is_paid = 0";
            $log_id = intval($GLOBALS['db']->getOne($sql));
            if ($log_id > 0)
            {
                /* 未付款，更新支付金额 */
                $sql = "UPDATE " . $GLOBALS['ecs']->table('pay_log') .
                        " SET order_amount = '$order_amount' " .
                        "WHERE log_id = '$log_id' LIMIT 1";
            }
            else
            {
                /* 已付款，生成新的pay_log */
                $sql = "INSERT INTO " . $GLOBALS['ecs']->table('pay_log') .
                        " (order_id, order_amount, order_type, is_paid)" .
                        "VALUES('$order_id', '$order_amount', '" . PAY_ORDER . "', 0)";
            }
            $GLOBALS['db']->query($sql);
        }
    }
}
/**
 * 更新支付金额
 * 如果支付ID为支付宝修改为已支付
 * @param   int     $order_id   订单id
 */
function update_pay($order_id,$pay_id)
{
    $order_id = intval($order_id);
    if ($order_id > 0)
    {
        $sql = "SELECT order_amount FROM " . $GLOBALS['ecs']->table('order_info') .
                " WHERE order_id = '$order_id'";
        $order_amount = $GLOBALS['db']->getOne($sql);
        if (!is_null($order_amount))
        {
            $sql = "SELECT log_id FROM " . $GLOBALS['ecs']->table('pay_log') .
                    " WHERE order_id = '$order_id'" .
                    " AND order_type = '" . PAY_ORDER . "'" ;
            $log_id = intval($GLOBALS['db']->getOne($sql));
            if ($pay_id == 1)
            {
                /* 支付宝修改为已支付 */
                $sql = "UPDATE " . $GLOBALS['ecs']->table('pay_log') .
                        " SET order_amount = '$order_amount',is_paid = '1' " .
                        "WHERE log_id = '$log_id' LIMIT 1";
            }
            else
            {   /*货到付款只修改金额*/
                $sql = "UPDATE " . $GLOBALS['ecs']->table('pay_log') .
                        " SET order_amount = '$order_amount',is_paid = '0' " .
                        "WHERE log_id = '$log_id' LIMIT 1";
            }
            $GLOBALS['db']->query($sql);
        }
    }
}

/**
 * 取得供货商列表
 * @return array    二维数组
 */
function get_suppliers_list()
{
    $sql = 'SELECT *
            FROM ' . $GLOBALS['ecs']->table('suppliers') . '
            WHERE is_check = 1
            ORDER BY suppliers_name ASC';
    $res = $GLOBALS['db']->getAll($sql);

    if (!is_array($res))
    {
        $res = array();
    }

    return $res;
}

/**
 * 取得订单商品
 * @param   array     $order  订单数组
 * @return array
 */
function get_order_goods($order)
{
    $goods_list = array();
    $goods_attr = array();
    $sql = "SELECT o.*, g.suppliers_id AS suppliers_id,IF(o.product_id > 0, p.product_number, g.goods_number) AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name, p.product_sn " .
            "FROM " . $GLOBALS['ecs']->table('order_goods') . " AS o ".
            "LEFT JOIN " . $GLOBALS['ecs']->table('products') . " AS p ON o.product_id = p.product_id " .
            "LEFT JOIN " . $GLOBALS['ecs']->table('goods') . " AS g ON o.goods_id = g.goods_id " .
            "LEFT JOIN " . $GLOBALS['ecs']->table('brand') . " AS b ON g.brand_id = b.brand_id " .
            "WHERE o.order_id = '$order[order_id]' ";
    $res = $GLOBALS['db']->query($sql);
    while ($row = $GLOBALS['db']->fetchRow($res))
    {
        // 虚拟商品支持
        if ($row['is_real'] == 0)
        {
            /* 取得语言项 */
            $filename = ROOT_PATH . 'plugins/' . $row['extension_code'] . '/languages/common_' . $GLOBALS['_CFG']['lang'] . '.php';
            if (file_exists($filename))
            {
                include_once($filename);
                if (!empty($GLOBALS['_LANG'][$row['extension_code'].'_link']))
                {
                    $row['goods_name'] = $row['goods_name'] . sprintf($GLOBALS['_LANG'][$row['extension_code'].'_link'], $row['goods_id'], $order['order_sn']);
                }
            }
        }

        $row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
        $row['formated_goods_price']    = price_format($row['goods_price']);

        $goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

        if ($row['extension_code'] == 'package_buy')
        {
            $row['storage'] = '';
            $row['brand_name'] = '';
            $row['package_goods_list'] = get_package_goods_list($row['goods_id']);
        }

        //处理货品id
        $row['product_id'] = empty($row['product_id']) ? 0 : $row['product_id'];

        $goods_list[] = $row;
    }

    $attr = array();
    $arr  = array();
    foreach ($goods_attr AS $index => $array_val)
    {
        foreach ($array_val AS $value)
        {
            $arr = explode(':', $value);//以 : 号将属性拆开
            $attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
        }
    }

    return array('goods_list' => $goods_list, 'attr' => $attr);
}

/**
 * 取得礼包列表
 * @param   integer     $package_id  订单商品表礼包类商品id
 * @return array
 */
function get_package_goods_list($package_id)
{
    $sql = "SELECT pg.goods_id, g.goods_name, (CASE WHEN pg.product_id > 0 THEN p.product_number ELSE g.goods_number END) AS goods_number, p.goods_attr, p.product_id, pg.goods_number AS
            order_goods_number, g.goods_sn, g.is_real, p.product_sn
            FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg
                LEFT JOIN " .$GLOBALS['ecs']->table('goods') . " AS g ON pg.goods_id = g.goods_id
                LEFT JOIN " . $GLOBALS['ecs']->table('products') . " AS p ON pg.product_id = p.product_id
            WHERE pg.package_id = '$package_id'";
    $resource = $GLOBALS['db']->query($sql);
    if (!$resource)
    {
        return array();
    }

    $row = array();

    /* 生成结果数组 取存在货品的商品id 组合商品id与货品id */
    $good_product_str = '';
    while ($_row = $GLOBALS['db']->fetch_array($resource))
    {
        if ($_row['product_id'] > 0)
        {
            /* 取存商品id */
            $good_product_str .= ',' . $_row['goods_id'];

            /* 组合商品id与货品id */
            $_row['g_p'] = $_row['goods_id'] . '_' . $_row['product_id'];
        }
        else
        {
            /* 组合商品id与货品id */
            $_row['g_p'] = $_row['goods_id'];
        }

        //生成结果数组
        $row[] = $_row;
    }
    $good_product_str = trim($good_product_str, ',');

    /* 释放空间 */
    unset($resource, $_row, $sql);

    /* 取商品属性 */
    if ($good_product_str != '')
    {
        $sql = "SELECT ga.goods_attr_id, ga.attr_value, ga.attr_price, a.attr_name
                FROM " .$GLOBALS['ecs']->table('goods_attr'). " AS ga, " .$GLOBALS['ecs']->table('attribute'). " AS a
                WHERE a.attr_id = ga.attr_id
                AND a.attr_type = 1
                AND goods_id IN ($good_product_str)";
        $result_goods_attr = $GLOBALS['db']->getAll($sql);

        $_goods_attr = array();
        foreach ($result_goods_attr as $value)
        {
            $_goods_attr[$value['goods_attr_id']] = $value;
        }
    }

    /* 过滤货品 */
    $format[0] = "%s:%s[%d] <br>";
    $format[1] = "%s--[%d]";
    foreach ($row as $key => $value)
    {
        if ($value['goods_attr'] != '')
        {
            $goods_attr_array = explode('|', $value['goods_attr']);

            $goods_attr = array();
            foreach ($goods_attr_array as $_attr)
            {
                $goods_attr[] = sprintf($format[0], $_goods_attr[$_attr]['attr_name'], $_goods_attr[$_attr]['attr_value'], $_goods_attr[$_attr]['attr_price']);
            }

            $row[$key]['goods_attr_str'] = implode('', $goods_attr);
        }

        $row[$key]['goods_name'] = sprintf($format[1], $value['goods_name'], $value['order_goods_number']);
    }

    return $row;


//    $sql = "SELECT pg.goods_id, CONCAT(g.goods_name, ' -- [', pg.goods_number, ']') AS goods_name,
//            g.goods_number, pg.goods_number AS order_goods_number, g.goods_sn, g.is_real " .
//            "FROM " . $GLOBALS['ecs']->table('package_goods') . " AS pg, " .
//                $GLOBALS['ecs']->table('goods') . " AS g " .
//            "WHERE pg.package_id = '$package_id' " .
//            "AND pg.goods_id = g.goods_id ";
//    $row = $GLOBALS['db']->getAll($sql);
//
//    return $row;
}

/**
 * 订单单个商品或货品的已发货数量
 *
 * @param   int     $order_id       订单 id
 * @param   int     $goods_id       商品 id
 * @param   int     $product_id     货品 id
 *
 * @return  int
 */
function order_delivery_num($order_id, $goods_id, $product_id = 0)
{
    $sql = 'SELECT SUM(G.send_number) AS sums
            FROM ' . $GLOBALS['ecs']->table('delivery_goods') . ' AS G, ' . $GLOBALS['ecs']->table('delivery_order') . ' AS O
            WHERE O.delivery_id = G.delivery_id
            AND O.status = 0
            AND O.order_id = ' . $order_id . '
            AND G.extension_code <> "package_buy"
            AND G.goods_id = ' . $goods_id;

    $sql .= ($product_id > 0) ? " AND G.product_id = '$product_id'" : '';

    $sum = $GLOBALS['db']->getOne($sql);

    if (empty($sum))
    {
        $sum = 0;
    }

    return $sum;
}

/**
 * 判断订单是否已发货（含部分发货）
 * @param   int     $order_id  订单 id
 * @return  int     1，已发货；0，未发货
 */
function order_deliveryed($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    $sql = 'SELECT COUNT(delivery_id)
            FROM ' . $GLOBALS['ecs']->table('delivery_order') . '
            WHERE order_id = \''. $order_id . '\'
            AND status = 0';
    $sum = $GLOBALS['db']->getOne($sql);

    if ($sum)
    {
        $return_res = 1;
    }

    return $return_res;
}

/**
 * 更新订单商品信息
 * @param   int     $order_id       订单 id
 * @param   array   $_sended        Array(‘商品id’ => ‘此单发货数量’)
 * @param   array   $goods_list
 * @return  Bool
 */
function update_order_goods($order_id, $_sended, $goods_list = array())
{
    if (!is_array($_sended) || empty($order_id))
    {
        return false;
    }

    foreach ($_sended as $key => $value)
    {
        // 超值礼包
        if (is_array($value))
        {
            if (!is_array($goods_list))
            {
                $goods_list = array();
            }

            foreach ($goods_list as $goods)
            {
                if (($key != $goods['rec_id']) || (!isset($goods['package_goods_list']) || !is_array($goods['package_goods_list'])))
                {
                    continue;
                }

                $goods['package_goods_list'] = package_goods($goods['package_goods_list'], $goods['goods_number'], $goods['order_id'], $goods['extension_code'], $goods['goods_id']);
                $pg_is_end = true;

                foreach ($goods['package_goods_list'] as $pg_key => $pg_value)
                {
                    if ($pg_value['order_send_number'] != $pg_value['sended'])
                    {
                        $pg_is_end = false; // 此超值礼包，此商品未全部发货

                        break;
                    }
                }

                // 超值礼包商品全部发货后更新订单商品库存
                if ($pg_is_end)
                {
                    $sql = "UPDATE " . $GLOBALS['ecs']->table('order_goods') . "
                            SET send_number = goods_number
                            WHERE order_id = '$order_id'
                            AND goods_id = '" . $goods['goods_id'] . "' ";

                    $GLOBALS['db']->query($sql, 'SILENT');
                }
            }
        }
        // 商品（实货）（货品）
        elseif (!is_array($value))
        {
            /* 检查是否为商品（实货）（货品） */
            foreach ($goods_list as $goods)
            {
                if ($goods['rec_id'] == $key && $goods['is_real'] == 1)
                {
                    $sql = "UPDATE " . $GLOBALS['ecs']->table('order_goods') . "
                            SET send_number = send_number + $value
                            WHERE order_id = '$order_id'
                            AND rec_id = '$key' ";
                    $GLOBALS['db']->query($sql, 'SILENT');
                    break;
                }
            }
        }
    }

    return true;
}

/**
 * 更新订单虚拟商品信息
 * @param   int     $order_id       订单 id
 * @param   array   $_sended        Array(‘商品id’ => ‘此单发货数量’)
 * @param   array   $virtual_goods  虚拟商品列表
 * @return  Bool
 */
function update_order_virtual_goods($order_id, $_sended, $virtual_goods)
{
    if (!is_array($_sended) || empty($order_id))
    {
        return false;
    }
    if (empty($virtual_goods))
    {
        return true;
    }
    elseif (!is_array($virtual_goods))
    {
        return false;
    }

    foreach ($virtual_goods as $goods)
    {
        $sql = "UPDATE ".$GLOBALS['ecs']->table('order_goods'). "
                SET send_number = send_number + '" . $goods['num'] . "'
                WHERE order_id = '" . $order_id . "'
                AND goods_id = '" . $goods['goods_id'] . "' ";
        if (!$GLOBALS['db']->query($sql, 'SILENT'))
        {
            return false;
        }
    }

    return true;
}

/**
 * 订单中的商品是否已经全部发货
 * @param   int     $order_id  订单 id
 * @return  int     1，全部发货；0，未全部发货
 */
function get_order_finish($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    $sql = 'SELECT COUNT(rec_id)
            FROM ' . $GLOBALS['ecs']->table('order_goods') . '
            WHERE order_id = \'' . $order_id . '\'
            AND goods_number > send_number';

    $sum = $GLOBALS['db']->getOne($sql);
    if (empty($sum))
    {
        $return_res = 1;
    }

    return $return_res;
}

/**
 * 判断订单的发货单是否全部发货
 * @param   int     $order_id  订单 id
 * @return  int     1，全部发货；0，未全部发货；-1，部分发货；-2，完全没发货；
 */
function get_all_delivery_finish($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    /* 未全部分单 */
    if (!get_order_finish($order_id))
    {
        return $return_res;
    }
    /* 已全部分单 */
    else
    {
        // 是否全部发货
        $sql = "SELECT COUNT(delivery_id)
                FROM " . $GLOBALS['ecs']->table('delivery_order') . "
                WHERE order_id = '$order_id'
                AND status = 2 ";
        $sum = $GLOBALS['db']->getOne($sql);
        // 全部发货
        if (empty($sum))
        {
            $return_res = 1;
        }
        // 未全部发货
        else
        {
            /* 订单全部发货中时：当前发货单总数 */
            $sql = "SELECT COUNT(delivery_id)
            FROM " . $GLOBALS['ecs']->table('delivery_order') . "
            WHERE order_id = '$order_id'
            AND status <> 1 ";
            $_sum = $GLOBALS['db']->getOne($sql);
            if ($_sum == $sum)
            {
                $return_res = -2; // 完全没发货
            }
            else
            {
                $return_res = -1; // 部分发货
            }
        }
    }

    return $return_res;
}

function trim_array_walk(&$array_value)
{
    if (is_array($array_value))
    {
        array_walk($array_value, 'trim_array_walk');
    }else{
        $array_value = trim($array_value);
    }
}

function intval_array_walk(&$array_value)
{
    if (is_array($array_value))
    {
        array_walk($array_value, 'intval_array_walk');
    }else{
        $array_value = intval($array_value);
    }
}

/**
 * 删除发货单(不包括已退货的单子)
 * @param   int     $order_id  订单 id
 * @return  int     1，成功；0，失败
 */
function del_order_delivery($order_id)
{
    $return_res = 0;

    if (empty($order_id))
    {
        return $return_res;
    }

    $sql = 'DELETE O, G
            FROM ' . $GLOBALS['ecs']->table('delivery_order') . ' AS O, ' . $GLOBALS['ecs']->table('delivery_goods') . ' AS G
            WHERE O.order_id = \'' . $order_id . '\'
            AND O.status = 0
            AND O.delivery_id = G.delivery_id';
    $query = $GLOBALS['db']->query($sql, 'SILENT');

    if ($query)
    {
        $return_res = 1;
    }

    return $return_res;
}

/**
 * 删除订单所有相关单子
 * @param   int     $order_id      订单 id
 * @param   int     $action_array  操作列表 Array('delivery', 'back', ......)
 * @return  int     1，成功；0，失败
 */
function del_delivery($order_id, $action_array)
{
    $return_res = 0;

    if (empty($order_id) || empty($action_array))
    {
        return $return_res;
    }

    $query_delivery = 1;
    $query_back = 1;
    if (in_array('delivery', $action_array))
    {
        $sql = 'DELETE O, G
                FROM ' . $GLOBALS['ecs']->table('delivery_order') . ' AS O, ' . $GLOBALS['ecs']->table('delivery_goods') . ' AS G
                WHERE O.order_id = \'' . $order_id . '\'
                AND O.delivery_id = G.delivery_id';
        $query_delivery = $GLOBALS['db']->query($sql, 'SILENT');
    }
    if (in_array('back', $action_array))
    {
        $sql = 'DELETE O, G
                FROM ' . $GLOBALS['ecs']->table('back_order') . ' AS O, ' . $GLOBALS['ecs']->table('back_goods') . ' AS G
                WHERE O.order_id = \'' . $order_id . '\'
                AND O.back_id = G.back_id';
        $query_back = $GLOBALS['db']->query($sql, 'SILENT');
    }

    if ($query_delivery && $query_back)
    {
        $return_res = 1;
    }

    return $return_res;
}

/**
 * 超级礼包发货数处理
 * @param   array   超级礼包商品列表
 * @param   int     发货数量
 * @param   int     订单ID
 * @param   varchar 虚拟代码
 * @param   int     礼包ID
 * @return  array   格式化结果
 */
function package_goods(&$package_goods, $goods_number, $order_id, $extension_code, $package_id)
{
    $return_array = array();

    if (count($package_goods) == 0 || !is_numeric($goods_number))
    {
        return $return_array;
    }

    foreach ($package_goods as $key=>$value)
    {
        $return_array[$key] = $value;
        $return_array[$key]['order_send_number'] = $value['order_goods_number'] * $goods_number;
        $return_array[$key]['sended'] = package_sended($package_id, $value['goods_id'], $order_id, $extension_code, $value['product_id']);
        $return_array[$key]['send'] = ($value['order_goods_number'] * $goods_number) - $return_array[$key]['sended'];
        $return_array[$key]['storage'] = $value['goods_number'];


        if ($return_array[$key]['send'] <= 0)
        {
            $return_array[$key]['send'] = $GLOBALS['_LANG']['act_good_delivery'];
            $return_array[$key]['readonly'] = 'readonly="readonly"';
        }

        /* 是否缺货 */
        if ($return_array[$key]['storage'] <= 0 && $GLOBALS['_CFG']['use_storage'] == '1')
        {
            $return_array[$key]['send'] = $GLOBALS['_LANG']['act_good_vacancy'];
            $return_array[$key]['readonly'] = 'readonly="readonly"';
        }
    }

    return $return_array;
}

/**
 * 获取超级礼包商品已发货数
 *
 * @param       int         $package_id         礼包ID
 * @param       int         $goods_id           礼包的产品ID
 * @param       int         $order_id           订单ID
 * @param       varchar     $extension_code     虚拟代码
 * @param       int         $product_id         货品id
 *
 * @return  int     数值
 */
function package_sended($package_id, $goods_id, $order_id, $extension_code, $product_id = 0)
{
    if (empty($package_id) || empty($goods_id) || empty($order_id) || empty($extension_code))
    {
        return false;
    }

    $sql = "SELECT SUM(DG.send_number)
            FROM " . $GLOBALS['ecs']->table('delivery_goods') . " AS DG, " . $GLOBALS['ecs']->table('delivery_order') . " AS o
            WHERE o.delivery_id = DG.delivery_id
            AND o.status IN (0, 2)
            AND o.order_id = '$order_id'
            AND DG.parent_id = '$package_id'
            AND DG.goods_id = '$goods_id'
            AND DG.extension_code = '$extension_code'";
    $sql .= ($product_id > 0) ? " AND DG.product_id = '$product_id'" : '';

    $send = $GLOBALS['db']->getOne($sql);

    return empty($send) ? 0 : $send;
}

/**
 * 改变订单中商品库存
 * @param   int     $order_id  订单 id
 * @param   array   $_sended   Array(‘商品id’ => ‘此单发货数量’)
 * @param   array   $goods_list
 * @return  Bool
 */
function change_order_goods_storage_split($order_id, $_sended, $goods_list = array())
{
    /* 参数检查 */
    if (!is_array($_sended) || empty($order_id))
    {
        return false;
    }

    foreach ($_sended as $key => $value)
    {
        // 商品（超值礼包）
        if (is_array($value))
        {
            if (!is_array($goods_list))
            {
                $goods_list = array();
            }
            foreach ($goods_list as $goods)
            {
                if (($key != $goods['rec_id']) || (!isset($goods['package_goods_list']) || !is_array($goods['package_goods_list'])))
                {
                    continue;
                }

                // 超值礼包无库存，只减超值礼包商品库存
                foreach ($goods['package_goods_list'] as $package_goods)
                {
                    if (!isset($value[$package_goods['goods_id']]))
                    {
                        continue;
                    }

                    // 减库存：商品（超值礼包）（实货）、商品（超值礼包）（虚货）
                    $sql = "UPDATE " . $GLOBALS['ecs']->table('goods') ."
                            SET goods_number = goods_number - '" . $value[$package_goods['goods_id']] . "'
                            WHERE goods_id = '" . $package_goods['goods_id'] . "' ";
                    $GLOBALS['db']->query($sql);
                }
            }
        }
        // 商品（实货）
        elseif (!is_array($value))
        {
            /* 检查是否为商品（实货） */
            foreach ($goods_list as $goods)
            {
                if ($goods['rec_id'] == $key && $goods['is_real'] == 1)
                {
                    $sql = "UPDATE " . $GLOBALS['ecs']->table('goods') . "
                            SET goods_number = goods_number - '" . $value . "'
                            WHERE goods_id = '" . $goods['goods_id'] . "' ";
                    $GLOBALS['db']->query($sql, 'SILENT');
                    break;
                }
            }
        }
    }

    return true;
}

/**
 *  超值礼包虚拟卡发货、跳过修改订单商品发货数的虚拟卡发货
 *
 * @access  public
 * @param   array      $goods      超值礼包虚拟商品列表数组
 * @param   string      $order_sn   本次操作的订单
 *
 * @return  boolen
 */
function package_virtual_card_shipping($goods, $order_sn)
{
    if (!is_array($goods))
    {
        return false;
    }

    /* 包含加密解密函数所在文件 */
    include_once(ROOT_PATH . 'includes/lib_code.php');

    // 取出超值礼包中的虚拟商品信息
    foreach ($goods as $virtual_goods_key => $virtual_goods_value)
    {
        /* 取出卡片信息 */
        $sql = "SELECT card_id, card_sn, card_password, end_date, crc32
                FROM ".$GLOBALS['ecs']->table('virtual_card')."
                WHERE goods_id = '" . $virtual_goods_value['goods_id'] . "'
                AND is_saled = 0
                LIMIT " . $virtual_goods_value['num'];
        $arr = $GLOBALS['db']->getAll($sql);
        /* 判断是否有库存 没有则推出循环 */
        if (count($arr) == 0)
        {
            continue;
        }

        $card_ids = array();
        $cards = array();

        foreach ($arr as $virtual_card)
        {
            $card_info = array();

            /* 卡号和密码解密 */
            if ($virtual_card['crc32'] == 0 || $virtual_card['crc32'] == crc32(AUTH_KEY))
            {
                $card_info['card_sn'] = decrypt($virtual_card['card_sn']);
                $card_info['card_password'] = decrypt($virtual_card['card_password']);
            }
            elseif ($virtual_card['crc32'] == crc32(OLD_AUTH_KEY))
            {
                $card_info['card_sn'] = decrypt($virtual_card['card_sn'], OLD_AUTH_KEY);
                $card_info['card_password'] = decrypt($virtual_card['card_password'], OLD_AUTH_KEY);
            }
            else
            {
                return false;
            }
            $card_info['end_date'] = date($GLOBALS['_CFG']['date_format'], $virtual_card['end_date']);
            $card_ids[] = $virtual_card['card_id'];
            $cards[] = $card_info;
        }

        /* 标记已经取出的卡片 */
        $sql = "UPDATE ".$GLOBALS['ecs']->table('virtual_card')." SET ".
           "is_saled = 1 ,".
           "order_sn = '$order_sn' ".
           "WHERE " . db_create_in($card_ids, 'card_id');
        if (!$GLOBALS['db']->query($sql))
        {
            return false;
        }

        /* 获取订单信息 */
        $sql = "SELECT order_id, order_sn, consignee, email FROM ".$GLOBALS['ecs']->table('order_info'). " WHERE order_sn = '$order_sn'";
        $order = $GLOBALS['db']->GetRow($sql);

        $cfg = $GLOBALS['_CFG']['send_ship_email'];
        if ($cfg == '1')
        {
            /* 发送邮件 */
            $GLOBALS['smarty']->assign('virtual_card',                   $cards);
            $GLOBALS['smarty']->assign('order',                          $order);
            $GLOBALS['smarty']->assign('goods',                          $virtual_goods_value);

            $GLOBALS['smarty']->assign('send_time', date('Y-m-d H:i:s'));
            $GLOBALS['smarty']->assign('shop_name', $GLOBALS['_CFG']['shop_name']);
            $GLOBALS['smarty']->assign('send_date', date('Y-m-d'));
            $GLOBALS['smarty']->assign('sent_date', date('Y-m-d'));

            $tpl = get_mail_template('virtual_card');
            $content = $GLOBALS['smarty']->fetch('str:' . $tpl['template_content']);
            send_mail($order['consignee'], $order['email'], $tpl['template_subject'], $content, $tpl['is_html']);
        }
    }

    return true;
}

/**
 * 获取站点根目录网址
 *
 * @access  private
 * @return  Bool
 */
function get_site_root_url()
{
    return 'http://' . $_SERVER['HTTP_HOST'] . str_replace('/' . ADMIN_PATH . '/order.php', '', PHP_SELF);

}


/**
 * 数字转金额大写
 *
 * @access  private
 * @return  Bool
 */
function cny($ns) { 
    static $cnums=array("零","壹","贰","叁","肆","伍","陆","柒","捌","玖"), 
        $cnyunits=array("圆 ","角 ","分 "), 
        $grees=array("拾 ","佰 ","仟 ","万 ","拾 ","佰 ","仟 ","亿 "); 
    list($ns1,$ns2)=explode(".",$ns,2); 
    $ns2=array_filter(array($ns2[1],$ns2[0])); 
    $ret=array_merge($ns2,array(implode("",_cny_map_unit(str_split($ns1),$grees)),"")); 
    $ret=implode("",array_reverse(_cny_map_unit($ret,$cnyunits))); 
    return str_replace(array_keys($cnums),$cnums,$ret); 
}
function _cny_map_unit($list,$units) { 
    $ul=count($units); 
    $xs=array(); 
    foreach (array_reverse($list) as $x) { 
        $l=count($xs); 
        if ($x!="0" || !($l%4)) $n=($x=='0'?'':$x).($units[($l-1)%$ul]); 
        else $n=is_numeric($xs[0][0])?$x:''; 
        array_unshift($xs,$n); 
    } 
    return $xs; 
}

/**
 * 更新订单库存
 * @param    int      $order_id              订单ID
 * @param    string   $operation             库存操作
 * @return   int      $operation_num         1为操作成功 2为操作失败 0为没有商品
 */
function up_order_stock($order_id,$operation){
       //获取订单区域ID
        $sql="SELECT agency_id,pay_id".
            " FROM ".$GLOBALS['ecs']->table('order_info').
            " WHERE order_id = $order_id ";
        $order_info=$GLOBALS['db']->getRow($sql); 

        $area_id=$order_info['agency_id'];
        $pay_id=$order_info['pay_id'];
        //获取订单商品
        $sql="SELECT goods_sku,goods_attr_sku,compose_note,goods_number ,goods_name,goods_attr".
            " FROM ".$GLOBALS['ecs']->table('order_goods').
            " WHERE order_id = $order_id ";
        $order_goods=$GLOBALS['db']->getAll($sql);
        if(!$order_goods){
            $operation_num['num']=0;
            return $operation_num;
        }
        //循环重组订单商品
        foreach ($order_goods as $key => $value) {
            //判断是否为组合商品
            if($value['compose_note']){
              foreach (explode(',', $value['compose_note']) as $k=> $v) {
                    $compose_note=explode('*', $v);
                    $goods[$compose_note['0']]['goods_number']=empty($goods[$compose_note['0']]['goods_number'])?$compose_note['1']*$value['goods_number']:$goods[$compose_note['0']]['goods_number']+$compose_note['1']*$value['goods_number'];
                    $goods[$compose_note['0']]['number']=$key+1;
              }
                $goods[$value['goods_sku']]['goods_number']=empty($goods[$value['goods_sku']]['goods_number'])?$value['goods_number']:$goods[$value['goods_sku']]['goods_number']+$value['goods_number'];
            }
            elseif($value['goods_attr_sku']){
                $goods[$value['goods_attr_sku']]['goods_number']=empty($goods[$value['goods_attr_sku']]['goods_number'])?$value['goods_number']:$goods[$value['goods_attr_sku']]['goods_number']+$value['goods_number'];
                $goods[$value['goods_attr_sku']]['number']=$key+1;
            }
            else{
                $goods[$value['goods_sku']]['goods_number']=empty($goods[$value['goods_sku']]['goods_number'])?$value['goods_number']:$goods[$value['goods_sku']]['goods_number']+$value['goods_number'];
                $goods[$value['goods_sku']]['number']=$key+1;
            }
        }
        switch ($operation) {
            case 'add':
            //添加库存
            foreach ($goods as $sku => $number) {
                $sql="UPDATE ".$GLOBALS['ecs']->table('goods_stock').
                 " set goods_number=(goods_number+".$number['goods_number'].")".
                 " WHERE area_id=$area_id AND goods_sku=$sku";
                $GLOBALS['db']->query($sql);
            }
                break;
            case 'reduce':
            //查询判断库存是否大于订单商品
            foreach ($goods as $sku => $number) {
                $sql="SELECT goods_number FROM".$GLOBALS['ecs']->table('goods_stock').
                     " WHERE area_id=$area_id AND goods_sku=$sku";
                $stock=$GLOBALS['db']->getOne($sql);
                if($stock<$number['goods_number']){
                    $operation_num['num']=2;
                    $operation_num['sku']=$sku;
                    return $operation_num;
                }
            }
            //减少库存
            foreach ($goods as $sku => $number) {
                $sql="UPDATE ".$GLOBALS['ecs']->table('goods_stock').
                 " set goods_number=(goods_number-".$number['goods_number'].")".
                 " WHERE area_id=$area_id AND goods_sku=$sku";
                $GLOBALS['db']->query($sql);
            }
                break;
            default:
                # code...
                break;
        }
        $operation_num['num']=1;
        return $operation_num;
}

?>
